Skip to content

Commit

Permalink
Merge pull request #1 from fsharp/udpate-proj-info
Browse files Browse the repository at this point in the history
  • Loading branch information
baronfel authored Oct 29, 2021
2 parents 1c01b09 + 4c6af37 commit 414950b
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 111 deletions.
92 changes: 46 additions & 46 deletions src/FsAutoComplete.Core/Commands.fs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ type NotificationEvent=
| Workspace of ProjectSystem.ProjectResponse
| AnalyzerMessage of messages: FSharp.Analyzers.SDK.Message [] * file: string<LocalPath>
| UnusedOpens of file: string<LocalPath> * opens: Range[]
| Lint of file: string<LocalPath> * warningsWithCodes: Lint.EnrichedLintWarning list
// | Lint of file: string<LocalPath> * warningsWithCodes: Lint.EnrichedLintWarning list
| UnusedDeclarations of file: string<LocalPath> * decls: (range * bool)[]
| SimplifyNames of file: string<LocalPath> * names: SimplifyNames.SimplifiableRange []
| Canceled of errorMessage: string
Expand All @@ -74,7 +74,7 @@ type Commands (checker: FSharpCompilerServiceChecker, state: State, backgroundSe

let mutable workspaceRoot: string option = rootPath
let mutable linterConfigFileRelativePath: string option = None
let mutable linterConfiguration: FSharpLint.Application.Lint.ConfigurationParam = FSharpLint.Application.Lint.ConfigurationParam.Default
// let mutable linterConfiguration: FSharpLint.Application.Lint.ConfigurationParam = FSharpLint.Application.Lint.ConfigurationParam.Default
let mutable lastVersionChecked = -1
let mutable lastCheckResult : ParseAndCheckResults option = None

Expand Down Expand Up @@ -851,32 +851,32 @@ type Commands (checker: FSharpCompilerServiceChecker, state: State, backgroundSe
member x.MethodsForSignatureHelp (tyRes : ParseAndCheckResults, pos: Pos, lines: ISourceText, triggerChar, possibleSessionKind) =
SignatureHelp.getSignatureHelpFor (tyRes, pos, lines, triggerChar, possibleSessionKind)

member x.Lint (file: string<LocalPath>): Async<unit> =
asyncResult {
let! (options, source) = state.TryGetFileCheckerOptionsWithSource file
match checker.TryGetRecentCheckResultsForFile(file, options) with
| None -> return ()
| Some tyRes ->
match tyRes.GetAST with
| None -> return ()
| Some tree ->
try
let! ctok = Async.CancellationToken
let! enrichedWarnings = Lint.lintWithConfiguration linterConfiguration ctok tree source tyRes.GetCheckResults
let res = CoreResponse.Res (file, enrichedWarnings)
notify.Trigger (NotificationEvent.Lint (file, enrichedWarnings))
return ()
with ex ->
commandsLogger.error (Log.setMessage "error while linting {file}: {message}"
>> Log.addContextDestructured "file" file
>> Log.addContextDestructured "message" ex.Message
>> Log.addExn ex)
return ()
}
|> Async.Ignore
|> x.AsCancellable file

|> AsyncResult.recoverCancellationIgnore
// member x.Lint (file: string<LocalPath>): Async<unit> =
// asyncResult {
// let! (options, source) = state.TryGetFileCheckerOptionsWithSource file
// match checker.TryGetRecentCheckResultsForFile(file, options) with
// | None -> return ()
// | Some tyRes ->
// match tyRes.GetAST with
// | None -> return ()
// | Some tree ->
// try
// let! ctok = Async.CancellationToken
// let! enrichedWarnings = Lint.lintWithConfiguration linterConfiguration ctok tree source tyRes.GetCheckResults
// let res = CoreResponse.Res (file, enrichedWarnings)
// notify.Trigger (NotificationEvent.Lint (file, enrichedWarnings))
// return ()
// with ex ->
// commandsLogger.error (Log.setMessage "error while linting {file}: {message}"
// >> Log.addContextDestructured "file" file
// >> Log.addContextDestructured "message" ex.Message
// >> Log.addExn ex)
// return ()
// }
// |> Async.Ignore
// |> x.AsCancellable file

// |> AsyncResult.recoverCancellationIgnore

member x.GetNamespaceSuggestions (tyRes : ParseAndCheckResults) (pos: Pos) (line: LineStr) =
async {
Expand Down Expand Up @@ -1205,27 +1205,27 @@ type Commands (checker: FSharpCompilerServiceChecker, state: State, backgroundSe

member __.SetWorkspaceRoot (root: string option) =
workspaceRoot <- root
linterConfiguration <- Lint.loadConfiguration workspaceRoot linterConfigFileRelativePath
// linterConfiguration <- Lint.loadConfiguration workspaceRoot linterConfigFileRelativePath

member __.SetLinterConfigRelativePath (relativePath: string option) =
linterConfigFileRelativePath <- relativePath
linterConfiguration <- Lint.loadConfiguration workspaceRoot linterConfigFileRelativePath

member __.FSharpLiterate (file: string<LocalPath>) =
async {
let cnt =
match state.TryGetFileSource file with
| Ok ctn -> ctn.ToString()
| _ -> File.ReadAllText (UMX.untag file)
let parsedFile =
if Utils.isAScript (UMX.untag file) then
FSharp.Formatting.Literate.Literate.ParseScriptString cnt
else
FSharp.Formatting.Literate.Literate.ParseMarkdownString cnt

let html = FSharp.Formatting.Literate.Literate.ToHtml parsedFile
return CoreResponse.Res html
}
// linterConfiguration <- Lint.loadConfiguration workspaceRoot linterConfigFileRelativePath

// member __.FSharpLiterate (file: string<LocalPath>) =
// async {
// let cnt =
// match state.TryGetFileSource file with
// | Ok ctn -> ctn.ToString()
// | _ -> File.ReadAllText (UMX.untag file)
// let parsedFile =
// if Utils.isAScript (UMX.untag file) then
// FSharp.Formatting.Literate.Literate.ParseScriptString cnt
// else
// FSharp.Formatting.Literate.Literate.ParseMarkdownString cnt

// let html = FSharp.Formatting.Literate.Literate.ToHtml parsedFile
// return CoreResponse.Res html
// }

member __.PipelineHints (tyRes : ParseAndCheckResults) =
result {
Expand Down
2 changes: 1 addition & 1 deletion src/FsAutoComplete.Core/FsAutoComplete.Core.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<Compile Include="SymbolCache.fs" />
<Compile Include="BackgroundServices.fs" />
<Compile Include="Fsdn.fs" />
<Compile Include="Lint.fs" />
<!-- <Compile Include="Lint.fs" /> -->
<Compile Include="SignatureHelp.fs" />
<Compile Include="Commands.fs" />
</ItemGroup>
Expand Down
2 changes: 0 additions & 2 deletions src/FsAutoComplete.Core/paket.references
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
FSharp.Compiler.Service
FSharpLint.Core
Ionide.ProjInfo
Ionide.ProjInfo.FCS
Ionide.ProjInfo.ProjectSystem
Expand All @@ -16,5 +15,4 @@ FsToolkit.ErrorHandling
Fantomas.Client

System.Reflection.Metadata
FSharp.Formatting
Microsoft.Build.Utilities.Core
112 changes: 56 additions & 56 deletions src/FsAutoComplete/FsAutoComplete.Lsp.fs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ type FSharpLspServer(backgroundServiceEnabled: bool, state: State, lspClient: FS
logger.info (Log.setMessage "ParseFile - Parsing {file}" >> Log.addContextDestructured "file" filePath)
do! (commands.Parse filePath content version (Some tfmConfig) |> Async.Ignore)

if config.Linter then do! (commands.Lint filePath |> Async.Ignore)
// if config.Linter then do! (commands.Lint filePath |> Async.Ignore)
if config.UnusedOpensAnalyzer then Async.Start (commands.CheckUnusedOpens filePath)
if config.UnusedDeclarationsAnalyzer then Async.Start (commands.CheckUnusedDeclarations filePath) //fire and forget this analyzer now that it's syncronous
if config.SimplifyNameAnalyzer then Async.Start (commands.CheckSimplifiedNames filePath)
Expand Down Expand Up @@ -295,44 +295,44 @@ type FSharpLspServer(backgroundServiceEnabled: bool, state: State, lspClient: FS
)
diagnosticCollections.SetFor(uri, "F# simplify names", diags)

| NotificationEvent.Lint (file, warnings) ->
let uri = Path.LocalPathToUri file
// let fs =
// warnings |> List.choose (fun w ->
// w.Warning.Details.SuggestedFix
// |> Option.bind (fun f ->
// let f = f.Force()
// let range = fcsRangeToLsp w.Warning.Details.Range
// f |> Option.map (fun f -> range, {Range = range; NewText = f.ToText})
// )
// )

let diags =
warnings
|> List.map(fun w ->
let range = fcsRangeToLsp w.Warning.Details.Range
let fixes =
match w.Warning.Details.SuggestedFix with
| None -> None
| Some lazyFix ->
match lazyFix.Value with
| None -> None
| Some fix ->
Some (box [ { Range = fcsRangeToLsp fix.FromRange; NewText = fix.ToText } ] )
let uri = Option.ofObj w.HelpUrl |> Option.map (fun url -> { Href = Some (Uri url) })
{ Range = range
Code = Some w.Code
Severity = Some DiagnosticSeverity.Information
Source = "F# Linter"
Message = w.Warning.Details.Message
RelatedInformation = None
Tags = None
Data = fixes
CodeDescription = uri }
)
|> List.sortBy (fun diag -> diag.Range)
|> List.toArray
diagnosticCollections.SetFor(uri, "F# Linter", diags)
// | NotificationEvent.Lint (file, warnings) ->
// let uri = Path.LocalPathToUri file
// // let fs =
// // warnings |> List.choose (fun w ->
// // w.Warning.Details.SuggestedFix
// // |> Option.bind (fun f ->
// // let f = f.Force()
// // let range = fcsRangeToLsp w.Warning.Details.Range
// // f |> Option.map (fun f -> range, {Range = range; NewText = f.ToText})
// // )
// // )

// let diags =
// warnings
// |> List.map(fun w ->
// let range = fcsRangeToLsp w.Warning.Details.Range
// let fixes =
// match w.Warning.Details.SuggestedFix with
// | None -> None
// | Some lazyFix ->
// match lazyFix.Value with
// | None -> None
// | Some fix ->
// Some (box [ { Range = fcsRangeToLsp fix.FromRange; NewText = fix.ToText } ] )
// let uri = Option.ofObj w.HelpUrl |> Option.map (fun url -> { Href = Some (Uri url) })
// { Range = range
// Code = Some w.Code
// Severity = Some DiagnosticSeverity.Information
// Source = "F# Linter"
// Message = w.Warning.Details.Message
// RelatedInformation = None
// Tags = None
// Data = fixes
// CodeDescription = uri }
// )
// |> List.sortBy (fun diag -> diag.Range)
// |> List.toArray
// diagnosticCollections.SetFor(uri, "F# Linter", diags)

| NotificationEvent.Canceled (msg) ->
let ntf = {Content = msg}
Expand Down Expand Up @@ -422,8 +422,8 @@ type FSharpLspServer(backgroundServiceEnabled: bool, state: State, lspClient: FS
let di = DirectoryInfo config.DotNetRoot
if di.Exists
then
let dotnetBinary =
if System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform (Runtime.InteropServices.OSPlatform.Windows)
let dotnetBinary =
if System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform (Runtime.InteropServices.OSPlatform.Windows)
then FileInfo (Path.Combine (di.FullName, "dotnet.exe"))
else FileInfo (Path.Combine (di.FullName, "dotnet"))
if dotnetBinary.Exists then commands.SetDotnetSDKRoot dotnetBinary else ()
Expand Down Expand Up @@ -774,7 +774,7 @@ type FSharpLspServer(backgroundServiceEnabled: bool, state: State, lspClient: FS

do! (commands.Parse filePath content doc.Version (Some tfmConfig) |> Async.Ignore)

if config.Linter then do! (commands.Lint filePath |> Async.Ignore)
// if config.Linter then do! (commands.Lint filePath |> Async.Ignore)
if config.UnusedOpensAnalyzer then Async.Start (commands.CheckUnusedOpens filePath)
if config.UnusedDeclarationsAnalyzer then Async.Start (commands.CheckUnusedDeclarations filePath)
if config.SimplifyNameAnalyzer then Async.Start (commands.CheckSimplifiedNames filePath)
Expand Down Expand Up @@ -2002,21 +2002,21 @@ type FSharpLspServer(backgroundServiceEnabled: bool, state: State, lspClient: FS

member __.ScriptFileProjectOptions = commands.ScriptFileProjectOptions

member __.FSharpLiterate (p: FSharpLiterateRequest) = async {
logger.info (Log.setMessage "FSharpLiterate Request: {parms}" >> Log.addContextDestructured "parms" p )
// member __.FSharpLiterate (p: FSharpLiterateRequest) = async {
// logger.info (Log.setMessage "FSharpLiterate Request: {parms}" >> Log.addContextDestructured "parms" p )

let fn = p.FileName |> Utils.normalizePath
let! res = commands.FSharpLiterate fn
let res =
match res with
| CoreResponse.InfoRes msg | CoreResponse.ErrorRes msg ->
LspResult.internalError msg
| CoreResponse.Res (res) ->
{ Content = CommandResponse.fsharpLiterate FsAutoComplete.JsonSerializer.writeJson res }
|> success
// let fn = p.FileName |> Utils.normalizePath
// let! res = commands.FSharpLiterate fn
// let res =
// match res with
// | CoreResponse.InfoRes msg | CoreResponse.ErrorRes msg ->
// LspResult.internalError msg
// | CoreResponse.Res (res) ->
// { Content = CommandResponse.fsharpLiterate FsAutoComplete.JsonSerializer.writeJson res }
// |> success

return res
}
// return res
// }

member x.FSharpPipelineHints (p: FSharpPipelineHintRequest) =
logger.info (Log.setMessage "FSharpPipelineHints Request: {parms}" >> Log.addContextDestructured "parms" p )
Expand Down Expand Up @@ -2057,7 +2057,7 @@ let startCore backgroundServiceEnabled toolsPath workspaceLoaderFactory =
|> Map.add "fsharp/documentation" (requestHandling (fun s p -> s.FSharpDocumentation(p) ))
|> Map.add "fsharp/documentationSymbol" (requestHandling (fun s p -> s.FSharpDocumentationSymbol(p) ))
|> Map.add "fsharp/loadAnalyzers" (requestHandling (fun s p -> s.LoadAnalyzers(p) ))
|> Map.add "fsharp/fsharpLiterate" (requestHandling (fun s p -> s.FSharpLiterate(p) ))
// |> Map.add "fsharp/fsharpLiterate" (requestHandling (fun s p -> s.FSharpLiterate(p) ))
|> Map.add "fsharp/pipelineHint" (requestHandling (fun s p -> s.FSharpPipelineHints(p) ))
// |> Map.add "fake/listTargets" (requestHandling (fun s p -> s.FakeTargets(p) ))
// |> Map.add "fake/runtimePath" (requestHandling (fun s p -> s.FakeRuntimePath(p) ))
Expand Down
1 change: 0 additions & 1 deletion src/FsAutoComplete/paket.references
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ Newtonsoft.Json
FSharp.Core
Microsoft.SourceLink.GitHub
System.Configuration.ConfigurationManager
FSharpLint.Core
Ionide.ProjInfo
Ionide.ProjInfo.ProjectSystem
#Fake.Runtime
Expand Down
9 changes: 5 additions & 4 deletions test/FsAutoComplete.Tests.Lsp/Program.fs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ let loaders = [
]

[<Tests>]
let tests =
let toolsPath = Ionide.ProjInfo.Init.init (System.IO.DirectoryInfo Environment.CurrentDirectory) None
let tests toolsPath =
testSequenced <| testList "lsp" [
for (name, workspaceLoaderFactory) in loaders do
testSequenced <| testList name [
Expand All @@ -56,7 +55,7 @@ let tests =
// commented out because FSDN is down
//fsdnTest state
uriTests
linterTests state
//linterTests state
formattingTests state
// fake isn't updated to FCS 39, disabling tests until that's resolved
//fakeInteropTests toolsPath
Expand All @@ -73,6 +72,8 @@ let tests =

[<EntryPoint>]
let main args =
let toolsPath = Ionide.ProjInfo.Init.init (System.IO.DirectoryInfo Environment.CurrentDirectory) None

let outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}"
let verbose = args |> Seq.contains "--debug"
let switch = LoggingLevelSwitch()
Expand Down Expand Up @@ -129,4 +130,4 @@ let main args =
failOnFocusedTests = true
printer = Expecto.Impl.TestPrinters.summaryPrinter defaultConfig.printer
verbosity = if verbose then Expecto.Logging.LogLevel.Debug else Expecto.Logging.LogLevel.Info }
runTestsWithArgsAndCancel cts.Token config fixedUpArgs tests
runTestsWithArgsAndCancel cts.Token config fixedUpArgs (tests toolsPath)
2 changes: 1 addition & 1 deletion test/FsAutoComplete.Tests.Lsp/TestCases/RenameTest/Test.fs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Test

let x = 123
let x = 123
5 changes: 5 additions & 0 deletions test/FsAutoComplete.Tests.Lsp/paket.references
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,8 @@ Expecto
Microsoft.NET.Test.Sdk
YoloDev.Expecto.TestSdk
AltCover

Microsoft.Build copy_local:false
Microsoft.Build.Framework copy_local:false
Microsoft.Build.Utilities.Core copy_local:false
Microsoft.Build.Tasks.Core copy_local: false

0 comments on commit 414950b

Please sign in to comment.