Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Adding a new DataAttribute to improve specifying realsig, optimize and baselines. #18161

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,72 +4,61 @@ open FSharp.Test
open FSharp.Test.Compiler
open Xunit

#nowarn 3391 //

module ComputedCollections =
let verifyCompilation compilation =
let verifyCompilation (compilation: CompilationUnit) =
compilation
|> asExe
|> withOptimize
|> withEmbeddedPdb
|> withEmbedAllSource
|> ignoreWarnings
|> verifyILBaseline

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"Int32RangeArrays.fs"|])>]
let ``Int32RangeArrays_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "Int32RangeArrays.fs")>]
let Int32RangeArrays_fs (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"Int32RangeLists.fs"|])>]
let ``Int32RangeLists_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "Int32RangeArrays.fs")>]
let ``Int32RangeLists_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "UInt64RangeArrays.fs")>]
let ``UInt64RangeArrays_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"UInt64RangeArrays.fs"|])>]
let ``UInt64RangeArrays_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "UInt64RangeLists.fs")>]
let ``UInt64RangeLists_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"UInt64RangeLists.fs"|])>]
let ``UInt64RangeLists_fs`` compilation =
compilation
|> verifyCompilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForNInRangeArrays.fs"|])>]
let ``ForNInRangeArrays_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForNInRangeArrays.fs")>]
let ``ForNInRangeArrays_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForNInRangeLists.fs"|])>]
let ``ForNInRangeLists_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForNInRangeLists.fs")>]
let ``ForNInRangeLists_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForXInArray_ToArray.fs"|])>]
let ``ForXInArray_ToArray_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForXInArray_ToArray.fs")>]
let ``ForXInArray_ToArray_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForXInArray_ToList.fs"|])>]
let ``ForXInArray_ToList_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForXInArray_ToList.fs")>]
let ``ForXInArray_ToList_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForXInList_ToArray.fs"|])>]
let ``ForXInList_ToArray_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForXInList_ToArray.fs")>]
let ``ForXInList_ToArray_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForXInList_ToList.fs"|])>]
let ``ForXInList_ToList_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForXInList_ToList.fs")>]
let ``ForXInList_ToList_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForXInSeq_ToArray.fs"|])>]
let ``ForXInSeq_ToArray_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForXInSeq_ToArray.fs")>]
let ``ForXInSeq_ToArray_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation

[<Theory; Directory(__SOURCE_DIRECTORY__, Includes=[|"ForXInSeq_ToList.fs"|])>]
let ``ForXInSeq_ToList_fs`` compilation =
compilation
|> verifyCompilation
[<Theory; FileInlineData(__SOURCE_DIRECTORY__, "ForXInSeq_ToList.fs")>]
let ``ForXInSeq_ToList_fs`` (compilation: CompilationHelper) =
verifyCompilation compilation
20 changes: 16 additions & 4 deletions tests/FSharp.Test.Utilities/Compiler.fs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ open FSharp.Test.ScriptHelpers
open Microsoft.CodeAnalysis
open Microsoft.CodeAnalysis.CSharp
open Xunit
open Xunit.Abstractions
open System
open System.Collections.Immutable
open System.IO
Expand All @@ -29,8 +30,8 @@ open System.Runtime.CompilerServices
open System.Runtime.InteropServices
open FSharp.Compiler.CodeAnalysis


module rec Compiler =

[<AutoOpen>]
type SourceUtilities () =
static member getCurrentMethodName([<CallerMemberName; Optional; DefaultParameterValue("")>] memberName: string) = memberName
Expand All @@ -57,7 +58,9 @@ module rec Compiler =
| FS of FSharpCompilationSource
| CS of CSharpCompilationSource
| IL of ILCompilationSource
override this.ToString() = match this with | FS fs -> fs.ToString() | _ -> (sprintf "%A" this )

override this.ToString() = match this with | FS fs -> fs.ToString() | _ -> (sprintf "%A" this)

member this.OutputDirectory =
let toString diOpt =
match diOpt: DirectoryInfo option with
Expand All @@ -67,6 +70,7 @@ module rec Compiler =
| FS fs -> fs.OutputDirectory |> toString
| CS cs -> cs.OutputDirectory |> toString
| _ -> raise (Exception "Not supported for this compilation type")

member this.WithStaticLink(staticLink: bool) = match this with | FS fs -> FS { fs with StaticLink = staticLink } | cu -> cu

type FSharpCompilationSource =
Expand All @@ -81,7 +85,11 @@ module rec Compiler =
References: CompilationUnit list
TargetFramework: TargetFramework
StaticLink: bool
}
}

// interface IXunitSerializable with
// member this.Serialize(info: IXunitSerializationInfo) = ()
// member this.Deserialize(info: IXunitSerializationInfo) =

member this.CreateOutputDirectory() =
match this.OutputDirectory with
Expand Down Expand Up @@ -537,6 +545,10 @@ module rec Compiler =
let withOptimize (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--optimize+" ] "withOptimize is only supported for F#" cUnit

let withOptimization (optimization: bool) (cUnit: CompilationUnit) : CompilationUnit =
let option = if optimization then "--optimize+" else "--optimize-"
withOptionsHelper [ option ] "withOptimization is only supported for F#" cUnit

let withFullPdb(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug:full" ] "withFullPdb is only supported for F#" cUnit

Expand Down Expand Up @@ -1795,10 +1807,10 @@ Actual:
let printSignatures cUnit = printSignaturesImpl None cUnit
let printSignaturesWith pageWidth cUnit = printSignaturesImpl (Some pageWidth) cUnit


let getImpliedSignatureHash cUnit =
let tcResults = cUnit |> typecheckResults
let hash = tcResults.CalculateSignatureHash()
match hash with
| Some h -> h
| None -> failwith "Implied signature hash returned 'None' which should not happen"

2 changes: 1 addition & 1 deletion tests/FSharp.Test.Utilities/CompilerAssert.fs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ type CompilationUtil private () =
with
| _ -> (errors, [||])
finally
try Directory.Delete(Path.GetDirectoryName ilFilePath, true) with _ -> ()
() //try Directory.Delete(Path.GetDirectoryName ilFilePath, true) with _ -> ()
TestCompilation.IL (source, compute)

and CompilationReference =
Expand Down
8 changes: 5 additions & 3 deletions tests/FSharp.Test.Utilities/DirectoryAttribute.fs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ type DirectoryAttribute(dir: string) =
if not <| FileSystem.FileExistsShim(f) then
failwithf "Requested file \"%s\" not found.\nAll files: %A.\nIncludes:%A." f allFiles includes

fsFiles
|> Array.map (fun fs -> createCompilationUnit dirInfo fs)
|> Seq.map (fun c -> [| c |])
let results =
fsFiles
|> Array.map (fun fs -> (createCompilationUnit dirInfo fs) :> obj)
|> Seq.map (fun c -> [| c |])
results
1 change: 1 addition & 0 deletions tests/FSharp.Test.Utilities/FSharp.Test.Utilities.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<Compile Include="Compiler.fs" />
<Compile Include="Peverifier.fs" />
<Compile Include="DirectoryAttribute.fs" />
<Compile Include="InlineFileDataAttribute.fs" />
<Compile Include="ReflectionHelper.fs" />
<Compile Include="SurfaceArea.fs" />
</ItemGroup>
Expand Down
160 changes: 160 additions & 0 deletions tests/FSharp.Test.Utilities/InlineFileDataAttribute.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
namespace FSharp.Test

open System
open System.Diagnostics
open System.Linq
open System.IO
open System.Reflection
open System.Runtime.CompilerServices
open System.Runtime.InteropServices

open Xunit
open Xunit.Abstractions
open Xunit.Sdk

open FSharp.Compiler.IO
open FSharp.Test.Compiler
open FSharp.Test.Utilities
open TestFramework

//[<AutoOpen>]
//module Extensions =
// let getCompilation (compilation: CompilationHelper): CompilationUnit =
// let c = unbox<CompilationHelper> compilation
// c.Value

type BooleanOptions =
| True = 1
| False = 2
| Both = 3
| None = 0

/// Attribute to use with Xunit's TheoryAttribute.
/// Takes a file, relative to current test suite's root.
/// Returns a CompilationUnit with encapsulated source code, error baseline and IL baseline (if any).
[<NoComparison; NoEquality>]
type FileInlineData (directory: string, filename: string) =
inherit DataAttribute()

let mutable optimize: BooleanOptions option = None
let mutable realsig: BooleanOptions option = None

static let computeBoolValues opt =
match opt with
| Some BooleanOptions.True -> [|Some true|]
| Some BooleanOptions.False -> [|Some false|]
| Some BooleanOptions.Both -> [|Some true; Some false|]
| _ -> [|None|]

static let convertToNullableBool (opt: bool option): obj =
match opt with
| None -> null
| Some opt -> box opt

member _.Optimize with set v = optimize <- Some v

member _.Realsig with set v = realsig <- Some v

override _.GetData _ =

let getOptions realsig optimize =

let compilationHelper = CompilationHelper(filename, directory, convertToNullableBool realsig, convertToNullableBool optimize)
[| box (compilationHelper) |]

let results =
let rsValues = computeBoolValues realsig
let optValues = computeBoolValues optimize
[|
for r in rsValues do
for o in optValues do
getOptions r o
|]

results

// realsig and optimized are boxed so null = not set, true or false = set
and CompilationHelper internal (filename: string, directory: string, realsig: obj, optimize: obj) =

let mutable filename = filename
let mutable directory = directory
let mutable realsig = realsig
let mutable optimize = optimize

let setRealInternalSignature compilation =
match realsig with
| null -> compilation
| realsig -> compilation |> withRealInternalSignature (unbox realsig)

let setOptimization compilation =
match optimize with
| null -> compilation
| optimize -> compilation |> withOptimization (unbox optimize)

static let getBaseline (opt: obj) prefix =
match opt with
| :? bool as b when b = true -> Some $"{prefix}On"
| :? bool as b when b = false -> Some $"{prefix}Off"
| _ -> None

static let combineBaselines realsigBsl optimizeBsl =
match realsigBsl, optimizeBsl with
| Some rs, Some opt -> Some $"{rs}{opt}"
| Some rs, None -> Some $"{rs}"
| None, Some opt -> Some $"{opt}"
| _ -> None

new() = CompilationHelper("", "", null, null)

// Define the implicit conversion operator
static member op_Implicit(helper: CompilationHelper) : CompilationUnit =
helper.Value ()

member _.Value(): CompilationUnit =
let frame = StackTrace().GetFrame(1) // Get the calling method's frame
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to use https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/caller-information instead?
Why exactly do we need it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@T-Gro , no. The Xunit.Sdk.DataAttribute.GetData override requires a MethodInfo instance. The caller-information attributes return the names of the member, the source file and line numbers.

Here is the Xunit description:
https://csharp-tokyo.github.io/xUnit-Hands-on/class_xunit_1_1_sdk_1_1_data_attribute.html#ab74ea9efe0a313e19ac0e8d8136a9071

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need it, because GetData _ = is how XUnit retrieves the test data instance, and in this case we are using the DirectoryAttribute to create a compiler instance, and so we need to 'pretend' we are being xunit. It is true that our DirectoryAttribute doesn't actually use it, but we do need an instance to even invoke the method. And there is a decent probablility that at some point in the future DirectoryAttribute.GetData() will use it, so I didn't want to pass Unchecked.DefaultOf.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we reuse the functionality of DirectoryAttribute possibly we could extract createCompilationUnit from it into a module or maybe inherit?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@majocha --- I'm still trying to figure out what we need. But we can certainly refactor, if necessary once we understand the necessities.

let methodInfo = frame.GetMethod() :?> MethodInfo

let directoryAttribute = DirectoryAttribute(directory)
directoryAttribute.Includes <- [| filename |]

let realsigBsl = (getBaseline realsig ".RealInternalSignature")
let optimizeBsl = (getBaseline optimize ".Optimize")

match combineBaselines realsigBsl optimizeBsl with
| Some baseline -> directoryAttribute.BaselineSuffix <- baseline
| _ -> ()

let results = directoryAttribute.GetData methodInfo
if results.Count() <> 1 then failwith $"directoryAttribute returned incorrect number of results requires only 1: actual: {results.Count()}"
let arguments = results.First()
if arguments.Count() <> 1 then failwith $"directoryAttribute returned incorrect number of arguments requires only 1: actual: {arguments.Count()}"
let compilation = arguments.First()

match compilation with
| :? CompilationUnit as cu -> cu |> setRealInternalSignature |> setOptimization
| _ -> failwith "No compilation created"

override _.ToString(): string =
let file = $"File: {filename}"
let realsig =
match realsig with
| :? bool as b -> $" realsig: {b}"
| _ -> ""
let optimize =
match optimize with
| :? bool as b -> $" optimize: {b}"
| _ -> ""
file + realsig + optimize

interface IXunitSerializable with
member _.Serialize(info: IXunitSerializationInfo) =
info.AddValue("filename", filename)
info.AddValue("directory", directory)
info.AddValue("realsig", realsig)
info.AddValue("optimize", optimize)

member _.Deserialize(info: IXunitSerializationInfo) =
filename <- info.GetValue<string>("filename")
directory <- info.GetValue<string>("directory")
realsig <- info.GetValue<obj>("realsig")
optimize <- info.GetValue<obj>("optimize")
4 changes: 1 addition & 3 deletions tests/FSharp.Test.Utilities/ProjectGeneration.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1023,9 +1023,7 @@ type ProjectWorkflowBuilder

member this.DeleteProjectDir() =
if Directory.Exists initialProject.ProjectDir then
try
Directory.Delete(initialProject.ProjectDir, true)
with _ -> ()
() //try Directory.Delete(initialProject.ProjectDir, true) with _ -> ()

member this.Execute(workflow: Async<WorkflowContext>) =
try
Expand Down
2 changes: 1 addition & 1 deletion tests/FSharp.Test.Utilities/TestFramework.fs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ let tempDirectoryOfThisTestRun =

let cleanUpTemporaryDirectoryOfThisTestRun () =
if tempDirectoryOfThisTestRun.IsValueCreated then
try tempDirectoryOfThisTestRun.Value.Delete(true) with _ -> ()
() //try tempDirectoryOfThisTestRun.Value.Delete(true) with _ -> ()

let createTemporaryDirectory () =
tempDirectoryOfThisTestRun.Value
Expand Down
Loading
Loading