Release build fails when types leak from transitive dependency, Debug is fine - f#

I'm trying to explain a weird F# compiler behavior between Release and Debug configurations regarding transitive dependencies. I will use Newtonsoft.Json package as the base dependency here, because that's the furthest I managed to get in pinpointing the issue, and it makes the example a bit less abstract.
Let's create a library project called SerializerProject, referencing Newtonsoft.Json via paket. In this project there is only one module:
module Serializer =
open System.IO
open System.Text
open Newtonsoft.Json
type OptionConverter() =
inherit JsonConverter()
(* only the signature is important, the implementation
and other methods are not interesting *)
override x.WriteJson(writer: JsonWriter, value: obj, serializer: JsonSerializer) =
(* ... *)
let fromJson<'a> (bytes: byte []): 'a =
let s = Encoding.UTF8.GetString(bytes)
use sr = new StringReader(s)
use jr = new JsonTextReader(sr)
let serializer = JsonSerializer()
serializer.Converters.Add(OptionConverter())
serializer.Deserialize<'a>(jr)
Now let's create a second project in the same solution and reference SerializerProject via project reference. I'd like to use fromJson in my new project, that's why I referenced SerializerProject in the first place.
module MyModule =
open Serializer
(* This is here just so we reference the fromJson function *)
let deserializer bytes = fromJson bytes
This is the minimal example to reproduce the behavior.
Now when I build the solution in Debug configuration, everything compiles and works fine. But when I switch to Release, the compilation fails in the second project, in MyModule in the deserializer definition. The exact error message is this:
The type referenced through 'Newtonsoft.Json.JsonWriter' is defined in an assembly that is not referenced. You must add a reference to assembly 'Newtonsoft.Json'
I'm using Visual Studio 2015 Update 3, F# tools (fsc, fsi) show version 14.0.23413.0.
It kind of makes sense, because it's reading metadata of the SerializerProject and finds that public OptionConverter type leaks the type JsonWriter on its public WriteJson method (as well as other types and other methods, but this one is encountered first), but what makes me wonder is why this works in Debug mode and is only a problem in the Release mode.
What kind of extra operations does the compiler do that affect this?
Why is this not a problem in Debug build when the type defined in Newtonsoft.Json really leaks transitively into the second project?
As suggested in the comments I tried referencing Newtonsoft.Json and decompiling the second assembly with ILSpy to see whether inlining turned on by compiler optimizations is to blame here, but even in Release configuration the second assembly looks like this:
call !!0 [SerializerProject]Serializer::fromJson<!a>(uint8[])
The fromJson function has not been inlined to expose the JsonWriter type directly, so there seem to be something more subtle going on.
This isn't a blocking issue, I just made the converter types private as I don't want to use them from the outside anyway, but I'd like to dig deeper in F# compiler inner workings.

Related

How do I subscribe to an event implemented in F# from a C# client?

How do I subscribe to an event implemented in F# from a C# client?
I have the following code:
_dispatcher.SignInRequested += StartActivity(typeof(SignInActivity));
This line results in the following error:
Error CS0012 The type 'FSharpHandler<>' is defined in an assembly that
is not referenced. You must add a reference to assembly 'FSharp.Core,
Version=3.3.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
I attempted to troubleshoot and found this:
However, I do not understand the answer. My events are defined under a namespace and not a module. Hence, me not understanding the reasoning of that discussion.
I then tried adding the following reference to my C# project:
FSharp.Core 4.0.0.1
and
FSharp.Core 3.1.2.5
However, I still receive the same error.
When managing Nuget packages, I do not see the version "3.3.1.0" listed as an option.
Implementation Details:
The signature of the signin event from the C# client is the following:
public event FSharpHandler<Unit> SignInRequested;
I actually declare the event as the following:
let signInRequested = new Event<_>()
Any suggestions?
You need to have a look at the CLIEventAttribute . Events declared from F# cannot be used from C# unless they are declared with this attribute.

Can't see some properties in Excel Interop from F#

I'm using the Microsoft.Office.Interop.Excel library (version 14.0) from an F# application and I can't seem to be able to reference some of the properties defined in Interop's interfaces/classes.
For example, if I have a Worksheet object I can't do the following:
let sht = // Get the Worksheet
sht.PageSetup.CenterHeader <- // Set the header
It can't find CenterHeader as a property of the PageSetup interface, even though it's there if I view the Interop dll in the object browser.
Just for reference, the Interop dll that I'm using is from the VS directory: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Excel.dll
Update:
I actually spoke too soon. Unfortunately the suggested solution with the cast didn't work either. VS thinks it's OK but it fails at runtime with the following error:
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.IPageSetup'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208B4-0001-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
As I said in the comments, F# doesn't support type equivalence for embedded interop types, so if a C# project has Embed Interop Types enabled then the F# compiler may be unable to determine which version of the interop type to use. Since the type embedded in the C# output assembly has been stripped down to only the members used, this can make it so that the F# compiler is unable to see members that are present in the version of the type from the primary interop assembly.
The workaround is to turn off Embed Interop Types on the C# project.
This works for me:
#if INTERACTIVE
#r "office"
#r "Microsoft.Office.Interop.Excel"
#endif
open Microsoft.Office.Interop.Excel
let setCenterHeader fileName worksheet header =
let file = System.IO.FileInfo(fileName)
let excel = ApplicationClass()
try
// Make sure to use full path since this will
// be interpreted as relative to Excel's process,
// not currently executing one
let workbook = excel.Workbooks.Open(file.FullName)
let sheet = workbook.Worksheets.[worksheet] :?> Worksheet
sheet.PageSetup.CenterHeader <- header
workbook.Save()
finally
excel.Application.Quit()
setCenterHeader "TestWorksheet.xlsx" "Sheet1" "My header 1"
setCenterHeader "TestWorksheet.xlsx" "Sheet2" "My header 2"
setCenterHeader "TestWorksheet.xlsx" "Sheet3" "My header 3"
You might want to make sure you have matching versions of PIA and Office installed/used.

F# function changes type when compiled with standalone switch and referenced from another project

In a Visual Studio project for an F# library I have defined a function as
let inline Estimate (s : ^a seq) (f : float) (w : int) : float * float = ..
The type of Estimate is
val Estimate : s:seq<'a> -> f:float -> w:int -> float*float
Calling Estimate from a script within that project works as expected.
Now if I compile the project with the --standalone switch and reference the output DLL from another project, Estimate is shown to be
Estimate<'a,'a>(s: Collections.Generic.IEnumerabls<'a>, f: float, w:int) : float*float
i.e. it some reason now takes tuple arguments.
Thus the following does not work
let q, p = EstimationQuality.Estimate x f 1 // This value is not a function and cannot be applied
but calling it with tuple parameters works fine
let q, p = EstimationQuality.Estimate (x, f, 1) // No problem.
What's wrong here? Is it a bug in the compiler?
EDIT:
Digging a little deeper, it appears that the problem is linked with the use of LanguagePrimitives.GenericZero.
While the problem actually compiles with the tuple parameter call, i get a runtime error when Estimate is called.
An unhandled exception of type 'System.TypeInitializationException'
occurred in LibraryTest.dll
Additional information: The type initializer for
'GenericZeroDynamicImplTable`1' threw an exception.
Compiling an F# DLL which is intended to be used from F#, with the standalone switch is not a good idea.
Why? Because all the F# metadata is lost since the whole set of F# types are included in your DLL so those types get a different identity from the types of the F# application that call your DLL or fsi.
The caller assembly uses the types in Fsharp.Core.dll which now are not the same as the ones used in your standalone compiled DLL.
That's why you see the tupled arguments, as seen from C# which doesn't understand F# metadata at all.
Generic inline functions using static constraints break as well since they need the metadata to inline at the call site.
Compiling also the caller assembly as standalone would make things worse, then you will have 3 sets of Fsharp types with different identities.
I think the standalone switch is fine when used only in the 'end-user' application.

Using System.Collections.Immutable with F# and Mono

I am trying to make use of the ImmutableDictionary in F# using Mono. I'm using the Xamarin IDE.
I have set my target framework to Mono/.Net4.5 and imported the System.Collections.Immutable using the built in Nuget package manager.
The following line
open System.Collections.Immutable
is generating the following two errors
'/Users/UserName/Projects/Xamarin/OrderInfer/OrderInference/MyTest.fs(34,34): Error FS1109: A reference to the type 'System.Collections.Generic.IEnumerable'1' in assembly 'System.Runtime' was found, but the type could not be found in that assembly (FS1109) (MyTest)'
/Users/UserName/Projects/Xamarin/OrderInfer/OrderInference: Error FS1108: The type 'Lazy'2' is required here and is unavailable. You must add a reference to assembly 'System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. (FS1108) (OrderInference)
The 2nd error suggests I need to reference System.ComponentModel.Composition. Am I able to use it in Mono? If so, is there another assembly I need to reference?
EDIT:
Solution removed and reposted below as an answer
This problem can be solved by adding a reference to: 'System.ComponentModel.Composition'. In Xamarin's IDE, this is done by using the Edit References Dialog which can be found by right-clicking on the reference in your project. Go to the All tab and search for System.ComponentModel and just add the System.ComponentModel.Composition assembly.
I now have the following two assemblies installed:
System.Collections.Immutable.dll
System.ComponentModel.Composition.dll
My code now reads:
open System
open System.ComponentModel.Composition
open System.Collections.Immutable
type wordPairs = { pairs:ImmutableDictionary<string, string>; count:int}
let myPairs = {pairs = ImmutableDictionary.Create<string, string>(); count = 0}
Note: As gradbot pointed out (and Immo Landwerth later nitpicked about ;>> ), ImmutableDictionary is a abstract sealed class. And as such, it has no public constructors. So you need to use the .Create method.
ImmutableDictionary is abstract so new won't work. It does however provide a number of create methods.
ImmutableDictionary.Create<string, string>()

F# AsyncWaitOne and AsyncReadToEnd

I am working ti old F# code from Expert F#. However, the example doesn't build anymore.
The following two calls don't seem to exist:
semaphore.AsyncWaitOne(?millisecondsTimeout=timeout)
and
reader.ReadToEndAsync()
Does anyone know what these have been replaced with or if I am just missing a reference?
It's now called Async.AwaitWaitHandle.
AsyncReadToEnd is in the F# PowerPack.
By now, FSharp PowerPack project has been broken up into smaller modules for any further development.
Specifically, the AsyncStreamReader class and the extension methods for the reading from a StreamReader, WebClient, etc. the new project is FSharpx.Async.
1) AsyncWaitOne is now called Async.AwaitWaitHandle.
2) AsyncReadToEnd() extension method does not exists anymore in the FSharp.PowerPack.
It has been replaced with the AsyncStreamReader dedicated type that contains proper asynchronous implementation of stream reading (like ReadToEnd, ReadLine, etc.)
It can be used like that:
async {
use asyncReader = new AsyncStreamReader(stream)
return! asyncReader.ReadToEnd() }
Note: Once you have installed FSharp.PowerPack, the AsyncStreamReader type will be 'injected' in the Microsoft.FSharp.Control namespace

Resources