Skip to content

Commit

Permalink
Fixed reference issues.
Browse files Browse the repository at this point in the history
  • Loading branch information
ashmind committed May 14, 2017
1 parent 084cb5e commit 0ee30a7
Show file tree
Hide file tree
Showing 24 changed files with 272 additions and 34 deletions.
6 changes: 6 additions & 0 deletions Backup/Tests.Roslyn2.Net46.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
</PropertyGroup>

</Project>
8 changes: 3 additions & 5 deletions Common/Advanced/IRoslynSession.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
using JetBrains.Annotations;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;

namespace MirrorSharp.Advanced {
[PublicAPI]
public interface IRoslynSession {
[NotNull] Project Project { get; }
[PublicAPI, NotNull] Project Project { get; }
}
}
4 changes: 2 additions & 2 deletions Common/Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
<PackageProjectUrl>https://github.com/ashmind/mirrorsharp</PackageProjectUrl>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/ashmind/mirrorsharp.git</RepositoryUrl>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netstandard1.5' ">$(PackageTargetFallback);dnxcore50;portable-net45+win8+wp8+wpa81;portable-net45+win8</PackageTargetFallback>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netstandard1.5' ">$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;portable-net45+win8</PackageTargetFallback>
<RootNamespace>MirrorSharp</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="10.1.5" />
<PackageReference Include="JetBrains.Annotations" Version="10.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="2.0.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.0.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic" Version="2.0.0" />
Expand Down
6 changes: 6 additions & 0 deletions Common/Internal/Abstraction/ILanguageSession.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;

namespace MirrorSharp.Internal.Abstraction {
internal interface ILanguageSession : IDisposable {
[NotNull] string GetText();
void ReplaceText([CanBeNull] string newText, int start = 0, [CanBeNull] int? length = null);

[NotNull] Task<ImmutableArray<Diagnostic>> GetDiagnosticsAsync(CancellationToken cancellationToken);
}
}
1 change: 0 additions & 1 deletion Common/Internal/Handlers/ReplaceTextHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis.Text;
using MirrorSharp.Internal.Handlers.Shared;
using MirrorSharp.Internal.Results;

Expand Down
1 change: 0 additions & 1 deletion Common/Internal/Handlers/SetOptionsHandler.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
Expand Down
8 changes: 1 addition & 7 deletions Common/Internal/Handlers/SlowUpdateHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using MirrorSharp.Advanced;
using MirrorSharp.Internal.Reflection;
using MirrorSharp.Internal.Results;
Expand All @@ -24,14 +23,9 @@ public SlowUpdateHandler([CanBeNull] ISlowUpdateExtension extension) {
public char CommandId => CommandIds.SlowUpdate;

public async Task ExecuteAsync(AsyncData data, WorkSession session, ICommandResultSender sender, CancellationToken cancellationToken) {
var roslynSession = session.RoslynOrNull;
if (roslynSession == null)
return;

var compilation = await roslynSession.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
// Temporary suppression, need to figure out the best approach here.
// ReSharper disable once HeapView.BoxingAllocation
var diagnostics = (IReadOnlyList<Diagnostic>)await compilation.WithAnalyzers(roslynSession.Analyzers).GetAllDiagnosticsAsync(cancellationToken).ConfigureAwait(false);
var diagnostics = (IReadOnlyList<Diagnostic>)await session.LanguageSession.GetDiagnosticsAsync(cancellationToken).ConfigureAwait(false);
object extensionResult = null;
if (_extension != null) {
var mutableDiagnostics = diagnostics.ToList();
Expand Down
1 change: 0 additions & 1 deletion Common/Internal/Handlers/TypeCharHandler.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis.Text;
using MirrorSharp.Internal.Handlers.Shared;
using MirrorSharp.Internal.Results;

Expand Down
6 changes: 6 additions & 0 deletions Common/Internal/Roslyn/RoslynSession.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -60,6 +61,11 @@ public void ReplaceText(string newText, int start = 0, int? length = null) {
SourceText = SourceText.WithChanges(_oneTextChange);
}

public async Task<ImmutableArray<Diagnostic>> GetDiagnosticsAsync(CancellationToken cancellationToken) {
var compilation = await Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
return await compilation.WithAnalyzers(Analyzers).GetAllDiagnosticsAsync(cancellationToken).ConfigureAwait(false);
}

[NotNull] public IList<CodeAction> CurrentCodeActions { get; } = new List<CodeAction>();

[NotNull]
Expand Down
1 change: 1 addition & 0 deletions Common/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
[assembly: InternalsVisibleTo("MirrorSharp.Testing")]
[assembly: InternalsVisibleTo("MirrorSharp.Tests.Roslyn1")]
[assembly: InternalsVisibleTo("MirrorSharp.Tests.Roslyn2")]
[assembly: InternalsVisibleTo("MirrorSharp.Tests.Roslyn2.Net46")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
5 changes: 4 additions & 1 deletion FSharp/FSharp.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard1.6;net46</TargetFrameworks>
<AssemblyName>MirrorSharp.FSharp</AssemblyName>
<RootNamespace>MirrorSharp.FSharp</RootNamespace>
<TargetFrameworks>net46</TargetFrameworks>
<TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<TargetFrameworkProfile />
</PropertyGroup>

<ItemGroup>
Expand Down
25 changes: 21 additions & 4 deletions FSharp/FSharpLanguage.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using System.Collections.Immutable;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.FSharp.Compiler.AbstractIL.Internal;
using Microsoft.FSharp.Core;
using MirrorSharp.Internal.Abstraction;

namespace MirrorSharp.FSharp {
Expand All @@ -9,10 +13,23 @@ internal class FSharpLanguage : ILanguage {

public ParseOptions DefaultParseOptions => null;
public CompilationOptions DefaultCompilationOptions => null;
public ImmutableList<MetadataReference> DefaultAssemblyReferences => null;
public ImmutableList<MetadataReference> DefaultAssemblyReferences { get; }

static FSharpLanguage() {
Library.Shim.FileSystem = new RestrictedFileSystem();
}

public FSharpLanguage() {
var fsharpAssembly = typeof(FSharpOption<>).GetTypeInfo().Assembly;
DefaultAssemblyReferences = ImmutableList.Create<MetadataReference>(
// note: this currently does not work on .NET Core, which is why this project isn't netstandard
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(new Uri(fsharpAssembly.EscapedCodeBase).LocalPath)
);
}

public ILanguageSession CreateSession(string text, ParseOptions parseOptions, CompilationOptions compilationOptions, ImmutableList<MetadataReference> metadataReferences) {
return new FSharpSession(text);
return new FSharpSession(text, metadataReferences);
}

string ILanguage.Name => Name;
Expand Down
88 changes: 81 additions & 7 deletions FSharp/FSharpSession.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,92 @@
using MirrorSharp.Internal.Abstraction;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.FSharp.Collections;
using Microsoft.FSharp.Compiler;
using MirrorSharp.Internal.Abstraction;
using Microsoft.FSharp.Compiler.SourceCodeServices;
using Microsoft.FSharp.Core;
using Microsoft.FSharp.Control;

namespace MirrorSharp.FSharp {
internal class FSharpSession : ILanguageSession {
private string _text;
private bool _textChanged = false;

private FSharpChecker _checker;
private readonly FSharpChecker _checker;
private readonly FSharpProjectOptions _projectOptions;

public FSharpSession(string text) {
_checker = FSharpChecker.Create(0, false, false, false);
public FSharpSession(string text, ImmutableList<MetadataReference> metadataReferences) {
_checker = FSharpChecker.Create(null, null, null, false);
_text = text;

var otherOptions = new List<string> { "--noframework" };
foreach (var reference in metadataReferences) {
switch (reference) {
case PortableExecutableReference pe:
// ReSharper disable once HeapView.ObjectAllocation (Unavoidable? Not worth caching)
otherOptions.Add("-r:" + pe.FilePath);
break;
default: throw new NotSupportedException($"Metadata reference type {reference.GetType()} is not supported.");
}
}

_projectOptions = new FSharpProjectOptions(
"_",
projectFileNames: new[] { "_.fs" },
otherOptions: otherOptions.ToArray(),
referencedProjects: Array.Empty<Tuple<string, FSharpProjectOptions>>(),
isIncompleteTypeCheckEnvironment: true,
useScriptResolutionRules: false,
loadTime: DateTime.Now,
unresolvedReferences: null,
originalLoadReferences: FSharpList<Tuple<Range.range, string>>.Empty,
extraProjectInfo: null
);
}

public async Task<ImmutableArray<Diagnostic>> GetDiagnosticsAsync(CancellationToken cancellationToken) {
var (parsed, check) = await FSharpAsync.StartAsTask(
_checker.ParseAndCheckFileInProject("_.fs", 0, _text, _projectOptions, null), null, cancellationToken
).ConfigureAwait(false);
var checkSuccess = check as FSharpCheckFileAnswer.Succeeded;

var diagnostics = ImmutableArray.CreateBuilder<Diagnostic>(parsed.Errors.Length + (checkSuccess?.Item.Errors.Length ?? 0));
ConvertAndAddTo(diagnostics, parsed.Errors);

if (checkSuccess != null)
ConvertAndAddTo(diagnostics, checkSuccess.Item.Errors);

return diagnostics.MoveToImmutable();
}

private void ConvertAndAddTo(ImmutableArray<Diagnostic>.Builder diagnostics, FSharpErrorInfo[] errors) {
foreach (var error in errors) {
var severity = ConvertToDiagnosticSeverity(error.Severity);
var location = Location.Create(
"",
new TextSpan(0, 0),
new LinePositionSpan(
new LinePosition(error.StartLineAlternate, error.StartColumn),
new LinePosition(error.EndLineAlternate, error.EndColumn)
)
);

diagnostics.Add(Diagnostic.Create(
"FS", "Compiler",
error.Message,
severity, severity,
isEnabledByDefault: false,
warningLevel: 0,
location: location
));
}
}

private DiagnosticSeverity ConvertToDiagnosticSeverity(FSharpErrorSeverity errorSeverity) {
return Equals(errorSeverity, FSharpErrorSeverity.Error) ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning;
}

public string GetText() {
Expand All @@ -23,7 +98,6 @@ public void ReplaceText(string newText, int start = 0, int? length = null) {
_text = _text.Remove(start, length.Value);
if (newText?.Length > 0)
_text = _text.Insert(start, newText);
_textChanged = true;
}

public void Dispose() {
Expand Down
9 changes: 9 additions & 0 deletions FSharp/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

[assembly: InternalsVisibleTo("MirrorSharp.Tests.Roslyn2.Net46")]
75 changes: 75 additions & 0 deletions FSharp/RestrictedFileSystem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.FSharp.Compiler.AbstractIL.Internal;

namespace MirrorSharp.FSharp {
internal class RestrictedFileSystem : Library.Shim.IFileSystem {
public Assembly AssemblyLoad(AssemblyName assemblyName) {
return Assembly.Load(assemblyName);
}

public Assembly AssemblyLoadFrom(string fileName) {
throw new NotSupportedException();
}

public void FileDelete(string fileName) {
throw new NotSupportedException();
}

public Stream FileStreamCreateShim(string fileName) {
throw new NotSupportedException();
}

public Stream FileStreamReadShim(string fileName) {
throw new NotSupportedException();
}

public Stream FileStreamWriteExistingShim(string fileName) {
throw new NotSupportedException();
}

public string GetFullPathShim(string fileName) {
EnsureAllowed(fileName);
if (!Path.IsPathRooted(fileName))
throw new NotSupportedException();
return fileName;
}

public DateTime GetLastWriteTimeShim(string fileName) {
EnsureAllowed(fileName);
return File.GetLastWriteTime(fileName);
}

public string GetTempPathShim() {
throw new NotSupportedException();
}

public bool IsInvalidPathShim(string filename) {
return filename.IndexOfAny(Path.GetInvalidPathChars()) >= 0;
}

public bool IsPathRootedShim(string path) {
return Path.IsPathRooted(path);
}

public byte[] ReadAllBytesShim(string fileName) {
EnsureAllowed(fileName);
return File.ReadAllBytes(fileName);
}

public bool SafeExists(string fileName) {
EnsureAllowed(fileName);
return File.Exists(fileName);
}

[AssertionMethod]
private static void EnsureAllowed(string fileName) {
if (!fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
&& !fileName.EndsWith(".optdata", StringComparison.OrdinalIgnoreCase)
&& !fileName.EndsWith(".sigdata", StringComparison.OrdinalIgnoreCase))
throw new NotSupportedException();
}
}
}
6 changes: 6 additions & 0 deletions MirrorSharp.sln
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Tests.Shared", "Tests.Share
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp", "FSharp\FSharp.csproj", "{A904B17F-1015-4676-B731-32353C22C49D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests.Roslyn2.Net46", "Tests.Roslyn2.Net46\Tests.Roslyn2.Net46.csproj", "{7F531F1E-5AF6-4FC6-BF71-84EB00C1B1EC}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
Tests.Shared\MirrorSharp.Tests.Shared.projitems*{0a9078a1-bd26-4dc7-87bb-ded125f6218b}*SharedItemsImports = 13
Expand Down Expand Up @@ -72,6 +74,10 @@ Global
{A904B17F-1015-4676-B731-32353C22C49D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A904B17F-1015-4676-B731-32353C22C49D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A904B17F-1015-4676-B731-32353C22C49D}.Release|Any CPU.Build.0 = Release|Any CPU
{7F531F1E-5AF6-4FC6-BF71-84EB00C1B1EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F531F1E-5AF6-4FC6-BF71-84EB00C1B1EC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F531F1E-5AF6-4FC6-BF71-84EB00C1B1EC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F531F1E-5AF6-4FC6-BF71-84EB00C1B1EC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Loading

0 comments on commit 0ee30a7

Please sign in to comment.