Accessing Local Variable Information in FSI

It’s time to make first steps to the new improved FSI. I feel that I should start looking for ways to implement something from My wish list for FSI. Let’s begin from #3 and try to find a list of declared variables and functions.

Before execution of any piece of code, FSI compiles it and creates a new type in current assembly. This type contain all named variables as properties and named function as function. The latest unnamed variable/function stores in property that called ‘it‘. So, it means that we can collect all required information using reflection.

Below you can find my implementation of the function objects() that prints lists of declared variables and functions.

let objects() =
  let methods =
      |> Seq.filter (fun t ->
        t.CustomAttributes |> Seq.exists (fun a ->
          a.AttributeType = typeof<Microsoft.FSharp.Core.CompilationMappingAttribute>))
      |> Seq.sortBy (fun t -> t.Name)
      |> (fun t ->
        t.GetMethods() |> Seq.filter(fun m -> not(m.IsHideBySig)))
      |> Seq.concat
      |> List.ofSeq
  let var, func =
    Map.empty<string, System.Reflection.MethodInfo>
      |> List.foldBack (fun (m:System.Reflection.MethodInfo) map ->
              let name = if (not(m.IsSpecialName)) then m.Name
                         else m.Name.Substring(4)
              if ((m.IsSpecialName && (m.GetParameters().Length > 0)) ||
                  map.ContainsKey(name)) then map
              else map.Add(name, m))
      |> Map.toList
      |> List.partition (fun (_,m) -> m.IsSpecialName)

  let printList title ls =
    printfn "%s : %A" title ( ls |> fst |> List.sort )
  var  |> printList "Variables"
  func |> printList "Functions"

Now let’s look at a real-life example on the screenshot below.

One thought on “Accessing Local Variable Information in FSI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s