Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
64 changes: 48 additions & 16 deletions src/fsharp/NicePrint.fs
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -1121,14 +1121,20 @@ module private PrintTypes =
ty.GetAssemblyName()

/// Printing TAST objects
module private PrintTastMemberOrVals =
open PrintTypes
let private prettyLayoutOfMember denv typarInst (v: Val) =
module private PrintTastMemberOrVals =
open PrintTypes
let private prettyLayoutOfMemberShortOption denv typarInst (v:Val) short =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since this is a private function I think it's fine to leave the name as-is and just have the additional flag. Perhaps rename the flag to shortMemberDisplay?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ok will do. Thanks :)

let v = mkLocalValRef v
let membInfo = Option.get v.MemberInfo
let stat = PrintTypes.layoutMemberFlags membInfo.MemberFlags
let _tps, argInfos, rty, _ = GetTypeOfMemberInFSharpForm denv.g v

if short then
for argInfo in argInfos do
for _,info in argInfo do
info.Attribs <- []
info.Name <- None

let mkNameL niceMethodTypars tagFunction name =
let nameL =
DemangleOperatorNameAsLayout (tagFunction >> mkNav v.DefinitionRange) name
Expand All @@ -1143,15 +1149,21 @@ module private PrintTastMemberOrVals =

match membInfo.MemberFlags.MemberKind with
| MemberKind.Member ->
let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty
let nameL = mkNameL niceMethodTypars tagMember v.LogicalName
let resL = stat --- (nameL ^^ WordL.colon ^^ tauL)
let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty
let resL =
if short then tauL
else
let nameL = mkNameL niceMethodTypars tagMember v.LogicalName
stat --- (nameL ^^ WordL.colon ^^ tauL)
prettyTyparInst, resL
| MemberKind.ClassConstructor
| MemberKind.Constructor ->
let prettyTyparInst, _, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty
let newL = layoutAccessibility denv v.Accessibility WordL.keywordNew
let resL = stat ++ newL ^^ wordL (tagPunctuation ":") ^^ tauL
let resL =
if short then tauL
else
let newL = layoutAccessibility denv v.Accessibility WordL.keywordNew
stat ++ newL ^^ wordL (tagPunctuation ":") ^^ tauL
prettyTyparInst, resL
| MemberKind.PropertyGetSet ->
emptyTyparInst, stat
Expand All @@ -1160,17 +1172,23 @@ module private PrintTastMemberOrVals =
// use error recovery because intellisense on an incomplete file will show this
errorR(Error(FSComp.SR.tastInvalidFormForPropertyGetter(), v.Id.idRange))
let nameL = mkNameL [] tagProperty v.CoreDisplayName
let resL = stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordGet)
let resL =
if short then nameL --- (WordL.keywordWith ^^ WordL.keywordGet)
else stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordGet)
emptyTyparInst, resL
else
let argInfos =
match argInfos with
| [[(ty, _)]] when isUnitTy denv.g ty -> []
| _ -> argInfos

let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty
let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName
let resL = stat --- (nameL ^^ WordL.colon ^^ (if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet)))
let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty
let resL =
if short then
if isNil argInfos then tauL
else tauL --- (WordL.keywordWith ^^ WordL.keywordGet)
else
let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName
stat --- (nameL ^^ WordL.colon ^^ (if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet)))
prettyTyparInst, resL
| MemberKind.PropertySet ->
if argInfos.Length <> 1 || isNil argInfos.Head then
Expand All @@ -1182,9 +1200,20 @@ module private PrintTastMemberOrVals =
else
let argInfos, valueInfo = List.frontAndBack argInfos.Head
let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst (if isNil argInfos then [] else [argInfos]) (fst valueInfo)
let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName
let resL = stat --- (nameL ^^ wordL (tagPunctuation ":") ^^ (tauL --- (WordL.keywordWith ^^ WordL.keywordSet)))
let resL =
if short then
(tauL --- (WordL.keywordWith ^^ WordL.keywordSet))
else
let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName
stat --- (nameL ^^ wordL (tagPunctuation ":") ^^ (tauL --- (WordL.keywordWith ^^ WordL.keywordSet)))
prettyTyparInst, resL

let private prettyLayoutOfMemberShort denv typarInst (v:Val) = prettyLayoutOfMemberShortOption denv typarInst v true

let prettyLayoutOfMember denv typarInst (v:Val) = prettyLayoutOfMemberShortOption denv typarInst v false

let prettyLayoutOfMemberNoInstShort denv v =
prettyLayoutOfMemberShortOption denv emptyTyparInst v true |> snd

let private layoutNonMemberVal denv (tps, v: Val, tau, cxs) =
let env = SimplifyTypes.CollectInfo true [tau] cxs
Expand Down Expand Up @@ -2048,9 +2077,12 @@ let stringOfExnDef denv x = x |> TastDefinitionPrinting.layoutExnDefn denv |> sh
let stringOfFSAttrib denv x = x |> PrintTypes.layoutAttrib denv |> squareAngleL |> showL
let stringOfILAttrib denv x = x |> PrintTypes.layoutILAttrib denv |> squareAngleL |> showL



let layoutInferredSigOfModuleExpr showHeader denv infoReader ad m expr = InferredSigPrinting.layoutInferredSigOfModuleExpr showHeader denv infoReader ad m expr
let prettyLayoutOfValOrMember denv typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember denv typarInst v
let prettyLayoutOfValOrMember denv typarInst v = PrintTastMemberOrVals.prettyLayoutOfValOrMember denv typarInst v
let prettyLayoutOfValOrMemberNoInst denv v = PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv v
let prettyLayoutOfMemberNoInstShort denv v = PrintTastMemberOrVals.prettyLayoutOfMemberNoInstShort denv v
let prettyLayoutOfInstAndSig denv x = PrintTypes.prettyLayoutOfInstAndSig denv x

/// Generate text for comparing two types.
Expand Down
2 changes: 1 addition & 1 deletion src/fsharp/symbols/Symbols.fs
Original file line number Diff line number Diff line change
Expand Up @@ -2024,7 +2024,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item) =
member x.FormatLayout (denv:FSharpDisplayContext) =
match x.IsMember, d with
| true, V v ->
NicePrint.prettyLayoutOfValOrMemberNoInst { (denv.Contents cenv.g) with showMemberContainers=true } v.Deref
NicePrint.prettyLayoutOfMemberNoInstShort { (denv.Contents cenv.g) with showMemberContainers=true } v.Deref
| _,_ ->
checkIsResolved()
let ty =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type CodeLensDisplayService (view : IWpfTextView, buffer : ITextBuffer, layerNam
buffer.Changed.Add self.HandleBufferChanged
view.LayoutChanged.Add self.HandleLayoutChanged
)

/// <summary>
/// Enqueing an unit signals to the tagger that all visible line lens must be layouted again,
/// to respect single line changes.
Expand Down Expand Up @@ -159,10 +159,9 @@ type CodeLensDisplayService (view : IWpfTextView, buffer : ITextBuffer, layerNam
#else
ignore e
#endif

/// Public non-thread-safe method to add line lens for a given tracking span.
/// Returns an UIElement which can be used to add Ui elements and to remove the line lens later.

member self.AddCodeLens (trackingSpan:ITrackingSpan) =
if trackingSpan.TextBuffer <> buffer then failwith "TrackingSpan text buffer does not equal with CodeLens text buffer"
let Grid = self.AddTrackingSpan trackingSpan
Expand Down Expand Up @@ -220,8 +219,12 @@ type CodeLensDisplayService (view : IWpfTextView, buffer : ITextBuffer, layerNam

member self.HandleLayoutChanged (e:TextViewLayoutChangedEventArgs) =
try
// We can cancel existing stuff because the algorithm supports abortion without any data loss
self.LayoutChangedCts.Cancel()
self.LayoutChangedCts.Dispose()
self.LayoutChangedCts <- new CancellationTokenSource()
let buffer = e.NewSnapshot
let recentVisibleLineNumbers = Set [self.RecentLastVsblLineNmbr .. self.RecentLastVsblLineNmbr]
let recentVisibleLineNumbers = Set [self.RecentFirstVsblLineNmbr .. self.RecentLastVsblLineNmbr]
Comment thread
cartermp marked this conversation as resolved.
Resolved
let firstVisibleLineNumber, lastVisibleLineNumber =
let first, last =
view.TextViewLines.FirstVisibleLine,
Expand Down Expand Up @@ -286,10 +289,6 @@ type CodeLensDisplayService (view : IWpfTextView, buffer : ITextBuffer, layerNam
// Save the new first and last visible lines for tracking
self.RecentFirstVsblLineNmbr <- firstVisibleLineNumber
self.RecentLastVsblLineNmbr <- lastVisibleLineNumber
// We can cancel existing stuff because the algorithm supports abortion without any data loss
self.LayoutChangedCts.Cancel()
self.LayoutChangedCts.Dispose()
self.LayoutChangedCts <- new CancellationTokenSource()

self.AsyncCustomLayoutOperation visibleLineNumbers buffer
|> RoslynHelpers.StartAsyncSafe self.LayoutChangedCts.Token "HandleLayoutChanged"
Expand Down
51 changes: 29 additions & 22 deletions vsintegration/src/FSharp.Editor/CodeLens/FSharpCodeLensService.fs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,15 @@ type internal FSharpCodeLensService

override __.VisitTypeAbbrev( _, range) = Some range

override __.VisitLetOrUse(_, _, _, range) = Some range
override __.VisitLetOrUse(_, _, bindings, range) =
match bindings |> Seq.tryFind (fun b -> b.RangeOfHeadPat.StartLine = pos.Line) with
| Some entry ->
Some entry.RangeOfBindingAndRhs
| None ->
// We choose to use the default range because
// it wasn't possible to find the complete range
// including implementation code.
Some range

override __.VisitBinding (fn, binding) =
Some binding.RangeOfBindingAndRhs
Expand Down Expand Up @@ -178,8 +186,7 @@ type internal FSharpCodeLensService

let displayContext = Option.defaultValue displayContext maybeContext
let typeLayout = func.FormatLayout displayContext
let taggedText = ResizeArray()

let taggedText = ResizeArray()
Layout.renderL (Layout.taggedTextListR taggedText.Add) typeLayout |> ignore
let statusBar = StatusBar(serviceProvider.GetService<SVsStatusbar, IVsStatusbar>())
let navigation = QuickInfoNavigation(statusBar, checker, projectInfoManager, document, realPosition)
Expand All @@ -191,37 +198,37 @@ type internal FSharpCodeLensService
#endif
return None
else return None
with e ->
with e ->
#if DEBUG
logErrorf "Error in lazy line lens computation. %A" e
#else
ignore e
#endif
return None
}

let inline setNewResultsAndWarnIfOverriden fullDeclarationText value =
#if DEBUG
if newResults.ContainsKey fullDeclarationText then
logWarningf "New results already contains: %A" fullDeclarationText
#endif
newResults.[fullDeclarationText] <- value

for symbolUse in symbolUses do
if symbolUse.IsFromDefinition then
match symbolUse.Symbol with
| :? FSharpMemberOrFunctionOrValue as func when func.IsModuleValueOrMember || func.IsProperty ->
let funcID = func.FullName
let fullDeclarationText = funcID
let funcID = func.LogicalName + (func.FullType.ToString() |> hash |> string)
Comment thread
cartermp marked this conversation as resolved.
Resolved
// Use a combination of the the function name + the hashed value of the type signature
let fullTypeSignature = func.FullType.ToString()
// Try to re-use the last results
if lastResults.ContainsKey fullDeclarationText then
if lastResults.ContainsKey funcID then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since you're hashing the text, should lastResults have its key be an int rather than a string? This would avoid an extra allocation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

If we want to minimize allocations I need to look into this again.

Maybe it would be enough to make a dictionary which maps from function name to the hash of the full type (last time it was used) and then only compare the value/hash of the last type to change only the code lens above functions which type has really changed. Would that allocate less?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Generally no, it's preferable not to use a string as a key if you can get away with it. Although it's still all small allocations, if you're already hashing something then that would be adequate for a key.

Though generally it's recommended to use more information than just a hash for a key, since there can be hash collisions.

Alternatively, does this caching provide any notable benefits? That is, if nothing was cached, does it meaningfully affect UX when used?

@realvictorprm realvictorprm Jun 26, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Of course, I wouldn't apply it if it wouldn't be of benefit :D
The current problem is that the key isn't unqiue which results in code lenses which aren't removed.

I think about removing the |> hash as it's better to hash the whole string anyways (so no hash collisions, thanks for the reminder btw). Currently I cannot see any possibility to remove the usage of a string as key. The small allocation is still much better than what would result in not using the cache (because that's what you get if you don't want it :D).

// Make sure that the results are usable
let inline setNewResultsAndWarnIfOverridenLocal value = setNewResultsAndWarnIfOverriden fullDeclarationText value
let lastTrackingSpan, codeLens as lastResult = lastResults.[fullDeclarationText]
let inline setNewResultsAndWarnIfOverridenLocal value = setNewResultsAndWarnIfOverriden funcID value
let lastTrackingSpan, codeLens as lastResult = lastResults.[funcID]
if codeLens.FullTypeSignature = fullTypeSignature then
setNewResultsAndWarnIfOverridenLocal lastResult
oldResults.Remove fullDeclarationText |> ignore
oldResults.Remove funcID |> ignore
else
let declarationLine, range =
match visit func.DeclarationLocation.Start parsedInput with
Expand All @@ -241,19 +248,19 @@ type internal FSharpCodeLensService
fullTypeSignature,
null)
// The old results aren't computed at all, because the line might have changed create new results
tagsToUpdate.[lastTrackingSpan] <- (newTrackingSpan, fullDeclarationText, res)
tagsToUpdate.[lastTrackingSpan] <- (newTrackingSpan, funcID, res)
setNewResultsAndWarnIfOverridenLocal (newTrackingSpan, res)

oldResults.Remove fullDeclarationText |> ignore
oldResults.Remove funcID |> ignore
else
// The symbol might be completely new or has slightly changed.
// We need to track this and iterate over the left entries to ensure that there isn't anything
unattachedSymbols.Add((symbolUse, func, fullDeclarationText, fullTypeSignature))
unattachedSymbols.Add((symbolUse, func, funcID, fullTypeSignature))
| _ -> ()

// In best case this works quite `covfefe` fine because often enough we change only a small part of the file and not the complete.
for unattachedSymbol in unattachedSymbols do
let symbolUse, func, fullDeclarationText, fullTypeSignature = unattachedSymbol
let symbolUse, func, funcID, fullTypeSignature = unattachedSymbol
let declarationLine, range =
match visit func.DeclarationLocation.Start parsedInput with
| Some range -> range.StartLine - 1, range
Expand All @@ -272,8 +279,8 @@ type internal FSharpCodeLensService
let newTrackingSpan =
textSnapshot.CreateTrackingSpan(declarationSpan, SpanTrackingMode.EdgeExclusive)
if codeLens.Computed && (isNull codeLens.UiElement |> not) then
newResults.[fullDeclarationText] <- (newTrackingSpan, codeLens)
tagsToUpdate.[trackingSpan] <- (newTrackingSpan, fullDeclarationText, codeLens)
newResults.[funcID] <- (newTrackingSpan, codeLens)
tagsToUpdate.[trackingSpan] <- (newTrackingSpan, funcID, codeLens)
else
let res =
CodeLens(
Expand All @@ -282,8 +289,8 @@ type internal FSharpCodeLensService
fullTypeSignature,
null)
// The tag might be still valid but it hasn't been computed yet so create fresh results
tagsToUpdate.[trackingSpan] <- (newTrackingSpan, fullDeclarationText, res)
newResults.[fullDeclarationText] <- (newTrackingSpan, res)
tagsToUpdate.[trackingSpan] <- (newTrackingSpan, funcID, res)
newResults.[funcID] <- (newTrackingSpan, res)
let key = res.Key
oldResults.Remove key |> ignore // no need to check this entry again
| None ->
Expand All @@ -304,7 +311,7 @@ type internal FSharpCodeLensService
let trackingSpan =
textSnapshot.CreateTrackingSpan(declarationSpan, SpanTrackingMode.EdgeExclusive)
codeLensToAdd.Add (trackingSpan, res)
newResults.[fullDeclarationText] <- (trackingSpan, res)
newResults.[funcID] <- (trackingSpan, res)
with e ->
#if DEBUG
logExceptionWithContext (e, "Line Lens tracking tag span creation")
Expand Down Expand Up @@ -401,4 +408,4 @@ type internal FSharpCodeLensService
bufferChangedCts.Cancel() // Stop all ongoing async workflow.
bufferChangedCts.Dispose()
bufferChangedCts <- new CancellationTokenSource()
executeCodeLenseAsync () |> Async.Ignore |> RoslynHelpers.StartAsyncSafe bufferChangedCts.Token "Buffer Changed"
executeCodeLenseAsync () |> Async.Ignore |> RoslynHelpers.StartAsyncSafe bufferChangedCts.Token "Buffer Changed"