first commit -push

This commit is contained in:
dungtt
2025-10-15 15:15:53 +07:00
parent 674ae395be
commit a9577c5756
885 changed files with 74595 additions and 0 deletions

View File

@@ -0,0 +1,196 @@
using System.Text;
using System.Xml;
namespace RobotNet.WebApp.Scripts.Monaco.Documentation;
public class DocumentationComment(
string summaryText = "",
DocumentationItem[]? typeParamElements = null,
DocumentationItem[]? paramElements = null,
string returnsText = "",
string remarksText = "",
string exampleText = "",
string valueText = "",
DocumentationItem[]? exception = null)
{
public string SummaryText { get; } = summaryText;
public DocumentationItem[] TypeParamElements { get; } = typeParamElements ?? [];
public DocumentationItem[] ParamElements { get; } = paramElements ?? [];
public string ReturnsText { get; } = returnsText;
public string RemarksText { get; } = remarksText;
public string ExampleText { get; } = exampleText;
public string ValueText { get; } = valueText;
public DocumentationItem[] Exception { get; } = exception ?? [];
public static DocumentationComment? From(string xmlDocumentation, string lineEnding)
{
if (string.IsNullOrEmpty(xmlDocumentation))
return Empty;
var reader = new StringReader("<docroot>" + xmlDocumentation + "</docroot>");
var summaryText = new StringBuilder();
var typeParamElements = new List<DocumentationItemBuilder>();
var paramElements = new List<DocumentationItemBuilder>();
var returnsText = new StringBuilder();
var remarksText = new StringBuilder();
var exampleText = new StringBuilder();
var valueText = new StringBuilder();
var exception = new List<DocumentationItemBuilder>();
using (var xml = XmlReader.Create(reader))
{
try
{
xml.Read();
string? elementName = null;
StringBuilder? currentSectionBuilder = null;
do
{
if (xml.NodeType == XmlNodeType.Element)
{
elementName = xml.Name.ToLowerInvariant();
switch (elementName)
{
case "filterpriority":
xml.Skip();
break;
case "remarks":
currentSectionBuilder = remarksText;
break;
case "example":
currentSectionBuilder = exampleText;
break;
case "exception":
DocumentationItemBuilder exceptionInstance = new(GetCref(xml["cref"]).TrimEnd());
currentSectionBuilder = exceptionInstance.Documentation;
exception.Add(exceptionInstance);
break;
case "returns":
currentSectionBuilder = returnsText;
break;
case "summary":
currentSectionBuilder = summaryText;
break;
case "see":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(GetCref(xml["cref"]));
currentSectionBuilder.Append(xml["langword"]);
break;
case "seealso":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append("See also: ");
currentSectionBuilder.Append(GetCref(xml["cref"]));
break;
case "paramref":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(xml["name"]);
currentSectionBuilder.Append(' ');
break;
case "param":
DocumentationItemBuilder paramInstance = new(TrimMultiLineString(xml["name"] ?? "", lineEnding));
currentSectionBuilder = paramInstance.Documentation;
paramElements.Add(paramInstance);
break;
case "typeparamref":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(xml["name"]);
currentSectionBuilder.Append(' ');
break;
case "typeparam":
DocumentationItemBuilder typeParamInstance = new(TrimMultiLineString(xml["name"] ?? "", lineEnding));
currentSectionBuilder = typeParamInstance.Documentation;
typeParamElements.Add(typeParamInstance);
break;
case "value":
currentSectionBuilder = valueText;
break;
case "br":
case "para":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(lineEnding);
break;
}
}
else if (xml.NodeType == XmlNodeType.Text && currentSectionBuilder != null)
{
if (elementName == "code")
{
currentSectionBuilder.Append(xml.Value);
}
else
{
currentSectionBuilder.Append(TrimMultiLineString(xml.Value, lineEnding));
}
}
} while (xml.Read());
}
catch (Exception)
{
return null;
}
}
return new DocumentationComment(
summaryText.ToString(),
typeParamElements.Select(s => s.ConvertToDocumentedObject()).ToArray(),
paramElements.Select(s => s.ConvertToDocumentedObject()).ToArray(),
returnsText.ToString(),
remarksText.ToString(),
exampleText.ToString(),
valueText.ToString(),
exception.Select(s => s.ConvertToDocumentedObject()).ToArray());
}
private static string TrimMultiLineString(string input, string lineEnding)
{
var lines = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
return string.Join(lineEnding, lines.Select(l => TrimStartRetainingSingleLeadingSpace(l)));
}
private static string GetCref(string? cref)
{
if (cref == null || cref.Trim().Length == 0)
{
return "";
}
if (cref.Length < 2)
{
return cref;
}
if (cref.Substring(1, 1) == ":")
{
return string.Concat(cref.AsSpan(2, cref.Length - 2), " ");
}
return cref + " ";
}
private static string TrimStartRetainingSingleLeadingSpace(string input)
{
if (string.IsNullOrWhiteSpace(input))
return string.Empty;
if (!char.IsWhiteSpace(input[0]))
return input;
return $" {input.TrimStart()}";
}
public string GetParameterText(string name)
=> Array.Find(ParamElements, parameter => parameter.Name == name)?.Documentation ?? string.Empty;
public string GetTypeParameterText(string name)
=> Array.Find(TypeParamElements, typeParam => typeParam.Name == name)?.Documentation ?? string.Empty;
public static readonly DocumentationComment Empty = new();
private static readonly string[] separator = ["\n", "\r\n"];
}
class DocumentationItemBuilder(string name)
{
public string Name { get; set; } = name;
public StringBuilder Documentation { get; set; } = new StringBuilder();
public DocumentationItem ConvertToDocumentedObject()
{
return new DocumentationItem(Name, Documentation.ToString());
}
}

View File

@@ -0,0 +1,169 @@
using Microsoft.CodeAnalysis;
using System.Text;
using System.Xml;
namespace RobotNet.WebApp.Scripts.Monaco.Documentation;
public class DocumentationConverter
{/// <summary>
/// Converts the xml documentation string into a plain text string.
/// </summary>
public static string ConvertDocumentation(string xmlDocumentation, string lineEnding)
{
if (string.IsNullOrEmpty(xmlDocumentation))
return string.Empty;
var reader = new StringReader("<docroot>" + xmlDocumentation + "</docroot>");
using var xml = XmlReader.Create(reader);
var ret = new StringBuilder();
try
{
xml.Read();
string? elementName = null;
do
{
if (xml.NodeType == XmlNodeType.Element)
{
elementName = xml.Name.ToLowerInvariant();
switch (elementName)
{
case "filterpriority":
xml.Skip();
break;
case "remarks":
ret.Append(lineEnding);
ret.Append("Remarks:");
ret.Append(lineEnding);
break;
case "example":
ret.Append(lineEnding);
ret.Append("Example:");
ret.Append(lineEnding);
break;
case "exception":
ret.Append(lineEnding);
ret.Append(GetCref(xml["cref"]).TrimEnd());
ret.Append(": ");
break;
case "returns":
ret.Append(lineEnding);
ret.Append("Returns: ");
break;
case "see":
ret.Append(GetCref(xml["cref"]));
ret.Append(xml["langword"]);
break;
case "seealso":
ret.Append(lineEnding);
ret.Append("See also: ");
ret.Append(GetCref(xml["cref"]));
break;
case "paramref":
ret.Append(xml["name"]);
ret.Append(' ');
break;
case "typeparam":
ret.Append(lineEnding);
ret.Append('<');
ret.Append(TrimMultiLineString(xml["name"], lineEnding));
ret.Append(">: ");
break;
case "param":
ret.Append(lineEnding);
ret.Append(TrimMultiLineString(xml["name"], lineEnding));
ret.Append(": ");
break;
case "value":
ret.Append(lineEnding);
ret.Append("Value: ");
ret.Append(lineEnding);
break;
case "br":
case "para":
ret.Append(lineEnding);
break;
}
}
else if (xml.NodeType == XmlNodeType.Text)
{
if (elementName == "code")
{
ret.Append(xml.Value);
}
else
{
ret.Append(TrimMultiLineString(xml.Value, lineEnding));
}
}
} while (xml.Read());
}
catch (Exception)
{
return xmlDocumentation;
}
return ret.ToString();
}
private static readonly string[] separator = ["\n", "\r\n"];
private static string TrimMultiLineString(string? input, string lineEnding)
{
if (string.IsNullOrEmpty(input)) return "";
var lines = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
return string.Join(lineEnding, lines.Select(l => l.TrimStart()));
}
private static string GetCref(string? cref)
{
if (cref == null || cref.Trim().Length == 0)
{
return "";
}
if (cref.Length < 2)
{
return cref;
}
if (cref.Substring(1, 1) == ":")
{
return cref[2..] + " ";
}
return cref + " ";
}
public static DocumentationComment? GetStructuredDocumentation(string? xmlDocumentation, string lineEnding)
{
if (string.IsNullOrEmpty(xmlDocumentation)) return null;
return DocumentationComment.From(xmlDocumentation, lineEnding);
}
public static DocumentationComment? GetStructuredDocumentation(ISymbol symbol, string lineEnding = "\n")
{
return symbol switch
{
IParameterSymbol parameter => new DocumentationComment(summaryText: GetParameterDocumentation(parameter, lineEnding) ?? ""),
ITypeParameterSymbol typeParam => new DocumentationComment(summaryText: GetTypeParameterDocumentation(typeParam, lineEnding) ?? ""),
IAliasSymbol alias => new DocumentationComment(summaryText: GetAliasDocumentation(alias, lineEnding) ?? ""),
_ => GetStructuredDocumentation(symbol.GetDocumentationCommentXml(), lineEnding),
};
}
private static string? GetParameterDocumentation(IParameterSymbol parameter, string lineEnding = "\n")
{
var contaningSymbolDef = parameter.ContainingSymbol.OriginalDefinition;
return GetStructuredDocumentation(contaningSymbolDef.GetDocumentationCommentXml(), lineEnding)
?.GetParameterText(parameter.Name);
}
private static string? GetTypeParameterDocumentation(ITypeParameterSymbol typeParam, string lineEnding = "\n")
{
var contaningSymbol = typeParam.ContainingSymbol;
return GetStructuredDocumentation(contaningSymbol.GetDocumentationCommentXml(), lineEnding)
?.GetTypeParameterText(typeParam.Name);
}
private static string? GetAliasDocumentation(IAliasSymbol alias, string lineEnding = "\n")
{
return GetStructuredDocumentation(alias.Target.GetDocumentationCommentXml(), lineEnding)?.SummaryText;
}
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco.Documentation;
public class DocumentationItem(string name, string documentation)
{
public string Name { get; } = name;
public string Documentation { get; } = documentation;
}

View File

@@ -0,0 +1,16 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct MarkerData
{
public string Code { get; set; }
public int EndColumn { get; set; }
public int EndLineNumber { get; set; }
public string Message { get; set; }
public int ModelVersionId { get; set; }
public RelatedInformation[] RelatedInformation { get; set; }
public MarkerSeverity Severity { get; set; }
public string Source { get; set; }
public int StartColumn { get; set; }
public int StartLineNumber { get; set; }
public MarkerData[] Tags { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct ModelContentChange
{
public Range Range { get; set; }
public int RangeLength { get; set; }
public int RangeOffset { get; set; }
public string Text { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct ModelContentChangedEvent
{
public ModelContentChange[] Changes { get; set; }
public string Eol { get; set; }
public bool IsEolChange { get; set; }
public bool IsFlush { get; set; }
public bool IsRedoing { get; set; }
public bool IsUndoing { get; set; }
public int VersionId { get; set; }
}

View File

@@ -0,0 +1,11 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct RelatedInformation
{
public int EndColumn { get; set; }
public int EndLineNumber { get; set; }
public string Message { get; set; }
public string Resource { get; set; }
public int StartColumn { get; set; }
public int StartLineNumber { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct SingleEditOperation
{
public bool? ForceMoveMarkers { get; set; }
public Range Range { get; set; }
public string Text { get; set; }
}

View File

@@ -0,0 +1,34 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
namespace RobotNet.WebApp.Scripts.Monaco;
public class InvocationContext
{
public SemanticModel SemanticModel { get; }
public int Position { get; }
public SyntaxNode Receiver { get; }
public IEnumerable<TypeInfo> ArgumentTypes { get; }
public IEnumerable<SyntaxToken> Separators { get; }
public bool IsInStaticContext { get; }
public InvocationContext(SemanticModel semModel, int position, SyntaxNode receiver, ArgumentListSyntax argList, bool isStatic)
{
SemanticModel = semModel;
Position = position;
Receiver = receiver;
ArgumentTypes = argList.Arguments.Select(argument => semModel.GetTypeInfo(argument.Expression));
Separators = argList.Arguments.GetSeparators();
IsInStaticContext = isStatic;
}
public InvocationContext(SemanticModel semModel, int position, SyntaxNode receiver, AttributeArgumentListSyntax argList, bool isStatic)
{
SemanticModel = semModel;
Position = position;
Receiver = receiver;
ArgumentTypes = argList.Arguments.Select(argument => semModel.GetTypeInfo(argument.Expression));
Separators = argList.Arguments.GetSeparators();
IsInStaticContext = isStatic;
}
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct Command
{
public string Id { get; set; }
public string Title { get; set; }
public string? Tooltip { get; set; }
public object[]? Arguments { get; set; }
}

View File

@@ -0,0 +1,248 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
using RobotNet.WebApp.Scripts.Monaco.Editor;
using System.Collections.Immutable;
using System.Reflection;
using System.Text.RegularExpressions;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public static class CompletionExtensions
{
private static readonly Dictionary<string, CompletionItemKind> s_roslynTagToCompletionItemKind = new()
{
{ WellKnownTags.Public, CompletionItemKind.Keyword },
{ WellKnownTags.Protected, CompletionItemKind.Keyword },
{ WellKnownTags.Private, CompletionItemKind.Keyword },
{ WellKnownTags.Internal, CompletionItemKind.Keyword },
{ WellKnownTags.File, CompletionItemKind.File },
{ WellKnownTags.Project, CompletionItemKind.File },
{ WellKnownTags.Folder, CompletionItemKind.Folder },
{ WellKnownTags.Assembly, CompletionItemKind.File },
{ WellKnownTags.Class, CompletionItemKind.Class },
{ WellKnownTags.Constant, CompletionItemKind.Constant },
{ WellKnownTags.Delegate, CompletionItemKind.Function },
{ WellKnownTags.Enum, CompletionItemKind.Enum },
{ WellKnownTags.EnumMember, CompletionItemKind.EnumMember },
{ WellKnownTags.Event, CompletionItemKind.Event },
{ WellKnownTags.ExtensionMethod, CompletionItemKind.Method },
{ WellKnownTags.Field, CompletionItemKind.Field },
{ WellKnownTags.Interface, CompletionItemKind.Interface },
{ WellKnownTags.Intrinsic, CompletionItemKind.Text },
{ WellKnownTags.Keyword, CompletionItemKind.Keyword },
{ WellKnownTags.Label, CompletionItemKind.Text },
{ WellKnownTags.Local, CompletionItemKind.Variable },
{ WellKnownTags.Namespace, CompletionItemKind.Module },
{ WellKnownTags.Method, CompletionItemKind.Method },
{ WellKnownTags.Module, CompletionItemKind.Module },
{ WellKnownTags.Operator, CompletionItemKind.Operator },
{ WellKnownTags.Parameter, CompletionItemKind.Value },
{ WellKnownTags.Property, CompletionItemKind.Property },
{ WellKnownTags.RangeVariable, CompletionItemKind.Variable },
{ WellKnownTags.Reference, CompletionItemKind.Reference },
{ WellKnownTags.Structure, CompletionItemKind.Struct },
{ WellKnownTags.TypeParameter, CompletionItemKind.TypeParameter },
{ WellKnownTags.Snippet, CompletionItemKind.Snippet },
{ WellKnownTags.Error, CompletionItemKind.Text },
{ WellKnownTags.Warning, CompletionItemKind.Text },
};
private static CompletionTrigger GetCompletionTrigger(int kind, char? triggerCharacter, bool includeTriggerCharacter)
=> kind switch
{
1 => CompletionTrigger.Invoke,
// https://github.com/dotnet/roslyn/issues/42982: Passing a trigger character
// to GetCompletionsAsync causes a null ref currently.
2 when includeTriggerCharacter => CompletionTrigger.CreateInsertionTrigger((char)triggerCharacter!),
_ => CompletionTrigger.Invoke,
};
//private static readonly Regex EscapeRegex = new(@"([\\\$}])", RegexOptions.Compiled);
//private static string GetAdjustedInsertTextWithPosition(
// CompletionChange change,
// int originalPosition,
// int newOffset,
// string? prependText = null)
//{
// string newText = change.TextChange.NewText!;
// if (change.NewPosition is not int newPosition
// || newPosition >= change.TextChange.Span.Start + newText.Length)
// {
// return prependText + newText[newOffset..];
// }
// int midpoint = newPosition - change.TextChange.Span.Start;
// var beforeText = prependText + newText[newOffset..midpoint];
// if (beforeText != null) beforeText = EscapeRegex.Replace(beforeText, @"\$1");
// var afterText = newText[midpoint..];
// if (afterText != null) afterText = EscapeRegex.Replace(afterText, @"\$1");
// return beforeText + "$0" + afterText;
//}
private static ImmutableArray<char> BuildCommitCharacters(Microsoft.CodeAnalysis.Completion.CompletionList completions, ImmutableArray<CharacterSetModificationRule> characterRules, ImmutableArray<char>.Builder triggerCharactersBuilder)
{
if (completions is null) return [];
triggerCharactersBuilder.AddRange(completions.Rules.DefaultCommitCharacters);
foreach (var modifiedRule in characterRules)
{
switch (modifiedRule.Kind)
{
case CharacterSetModificationKind.Add:
triggerCharactersBuilder.AddRange(modifiedRule.Characters);
break;
case CharacterSetModificationKind.Remove:
for (int i = 0; i < triggerCharactersBuilder.Count; i++)
{
if (modifiedRule.Characters.Contains(triggerCharactersBuilder[i]))
{
triggerCharactersBuilder.RemoveAt(i);
i--;
}
}
break;
case CharacterSetModificationKind.Replace:
triggerCharactersBuilder.Clear();
triggerCharactersBuilder.AddRange(modifiedRule.Characters);
break;
}
}
if (completions.SuggestionModeItem is not null)
{
triggerCharactersBuilder.Remove(' ');
}
if (triggerCharactersBuilder.Capacity == triggerCharactersBuilder.Count)
{
return triggerCharactersBuilder.MoveToImmutable();
}
else
{
var result = triggerCharactersBuilder.ToImmutable();
triggerCharactersBuilder.Clear();
return result;
}
}
private static CompletionItemKind GetCompletionItemKind(ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
if (s_roslynTagToCompletionItemKind.TryGetValue(tag, out var itemKind))
{
return itemKind;
}
}
return CompletionItemKind.Text;
}
public static async Task<IEnumerable<CompletionItem>> GetCompletionAsync(this AdhocWorkspace workspace, DocumentId documentId, int line, int column, int kind, char? triggerCharacter)
{
if (triggerCharacter == ' ') return [];
var document = workspace.CurrentSolution.GetDocument(documentId);
if (document is null) return [];
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(line - 1, column - 1));
var completionService = CompletionService.GetService(document);
if (completionService == null) return [];
if (kind == 3 && !completionService.ShouldTriggerCompletion(sourceText, position, GetCompletionTrigger(kind - 1, triggerCharacter, includeTriggerCharacter: true)))
{
return [];
}
Microsoft.CodeAnalysis.Completion.CompletionList? completionList = null;
try
{
completionList = await completionService.GetCompletionsAsync(
document,
position,
GetCompletionTrigger(kind - 1, triggerCharacter, includeTriggerCharacter: false));
}
catch (Exception ex)
{
// Log the exception or handle it as needed
Console.WriteLine($"Error getting completions: position:{position} \n {ex}");
}
if (completionList is null || completionList.ItemsList.Count <= 0) return [];
var typedSpan = completionService.GetDefaultCompletionListSpan(sourceText, position);
string typedText = sourceText.GetSubText(typedSpan).ToString();
ImmutableArray<string> filteredItems = typedText != string.Empty
? [.. completionService.FilterItems(document, [.. completionList.ItemsList], typedText).Select(i => i.DisplayText)]
: [];
bool expectingImportedItems = workspace.Options.GetOption(new PerLanguageOption<bool?>("CompletionOptions", "ShowItemsFromUnimportedNamespaces", defaultValue: null), LanguageNames.CSharp) == true;
var syntax = await document.GetSyntaxTreeAsync();
var replacingSpanStartPosition = sourceText.Lines.GetLinePosition(typedSpan.Start);
var replacingSpanEndPosition = sourceText.Lines.GetLinePosition(typedSpan.End);
var triggerCharactersBuilder = ImmutableArray.CreateBuilder<char>(completionList.Rules.DefaultCommitCharacters.Length);
var completionsBuilder = new List<CompletionItem>();
foreach (var completion in completionList.ItemsList)
{
SingleEditOperation[]? additionalTextEdits = null;
char sortTextPrepend = '0';
if (!completion.Properties.TryGetValue("InsertionText", out string? insertText))
{
if (GetCompletionItemKind(completion.Tags) == CompletionItemKind.Keyword)
{
insertText = completion.DisplayText;
}
else
{
continue;
}
}
if (string.IsNullOrEmpty(insertText)) continue;
var commitCharacters = BuildCommitCharacters(completionList, completion.Rules.CommitCharacterRules, triggerCharactersBuilder).Select(c => c.ToString());
completionsBuilder.Add(new CompletionItem
{
Label = completion.DisplayTextPrefix + completion.DisplayText + completion.DisplayTextSuffix,
Kind = GetCompletionItemKind(completion.Tags),
Documentation = "",
InsertText = insertText,
Range = new Range
{
StartLineNumber = replacingSpanStartPosition.Line + 1,
EndLineNumber = replacingSpanEndPosition.Line + 1,
StartColumn = replacingSpanStartPosition.Character + 1,
EndColumn = replacingSpanEndPosition.Character + 1,
},
AdditionalTextEdits = additionalTextEdits,
// Ensure that unimported items are sorted after things already imported.
SortText = expectingImportedItems ? sortTextPrepend + completion.SortText : completion.SortText,
FilterText = completion.FilterText,
Detail = completion.InlineDescription,
Preselect = completion.Rules.MatchPriority == MatchPriority.Preselect || filteredItems.Contains(completion.DisplayText),
CommitCharacters = [.. commitCharacters],
Tags = null,
Command = null,
InsertTextRules = null,
});
}
return completionsBuilder;
}
}

View File

@@ -0,0 +1,21 @@
using RobotNet.WebApp.Scripts.Monaco.Editor;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionItem
{
public string Label { get; set; }
public CompletionItemKind Kind { get; set; }
public string? Documentation { get; set; }
public string InsertText { get; set; }
public Range Range { get; set; }
public SingleEditOperation[]? AdditionalTextEdits { get; set; }
public Command? Command { get; set; }
public string[]? CommitCharacters { get; set; }
public string? Detail { get; set; }
public string? FilterText { get; set; }
public CompletionItemInsertTextRule? InsertTextRules { get; set; }
public bool Preselect { get; set; }
public string? SortText { get; set; }
public int[]? Tags { get; set; }
}

View File

@@ -0,0 +1,15 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public enum CompletionItemInsertTextRule
{
None = 0,
/**
* Adjust whitespace/indentation of multiline insert texts to
* match the current line indentation.
*/
KeepWhitespace = 1,
/**
* `insertText` is a snippet.
*/
InsertAsSnippet = 4
}

View File

@@ -0,0 +1,33 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public enum CompletionItemKind
{
Method = 0,
Function = 1,
Constructor = 2,
Field = 3,
Variable = 4,
Class = 5,
Struct = 6,
Interface = 7,
Module = 8,
Property = 9,
Event = 10,
Operator = 11,
Unit = 12,
Value = 13,
Constant = 14,
Enum = 15,
EnumMember = 16,
Keyword = 17,
Text = 18,
Color = 19,
File = 20,
Reference = 21,
Customcolor = 22,
Folder = 23,
TypeParameter = 24,
User = 25,
Issue = 26,
Snippet = 27
}

View File

@@ -0,0 +1,8 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionItemLabel
{
public string? Description { get; set; }
public string? Detail { get; set; }
public string Label { get; set; }
}

View File

@@ -0,0 +1,9 @@
using RobotNet.WebApp.Scripts.Monaco;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionItemRanges
{
public Range Intert { get; set; }
public Range Replace { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public enum CompletionItemTag
{
Deprecated = 1
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionList
{
public bool? Incomplete { get; set; }
public CompletionItem[] Suggestions { get; set; }
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct ParameterInformation
{
public string Label { get; set; }
public MarkdownString? Documentation { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct SignatureHelp
{
public int ActiveParameter { get; set; }
public int ActiveSignature { get; set; }
public SignatureInformation[] Signatures { get; set; }
}

View File

@@ -0,0 +1,169 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using RobotNet.WebApp.Scripts.Monaco.Documentation;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public static class SignatureHelpExtensions
{
public static async Task<SignatureHelpResult?> GetSignatureHelpAsync(this Document document, int line, int column)
{
var invocation = await GetInvocation(document, line - 1, column - 1);
if (invocation is null) return null;
var response = new SignatureHelp();
foreach (var comma in invocation.Separators)
{
if (comma.Span.Start > invocation.Position)
{
break;
}
response.ActiveParameter += 1;
}
var signaturesSet = new HashSet<SignatureInformation>();
var bestScore = int.MinValue;
SignatureInformation? bestScoredItem = null;
var types = invocation.ArgumentTypes;
ISymbol? throughSymbol = null;
ISymbol? throughType = null;
var methodGroup = invocation.SemanticModel.GetMemberGroup(invocation.Receiver).OfType<IMethodSymbol>();
if (invocation.Receiver is MemberAccessExpressionSyntax syntax)
{
var throughExpression = syntax.Expression;
throughSymbol = invocation.SemanticModel.GetSpeculativeSymbolInfo(invocation.Position, throughExpression, SpeculativeBindingOption.BindAsExpression).Symbol;
throughType = invocation.SemanticModel.GetSpeculativeTypeInfo(invocation.Position, throughExpression, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
var includeInstance = throughSymbol != null && throughSymbol is not ITypeSymbol ||
throughExpression is LiteralExpressionSyntax ||
throughExpression is TypeOfExpressionSyntax;
var includeStatic = throughSymbol is INamedTypeSymbol || throughType != null;
methodGroup = methodGroup.Where(m => m.IsStatic && includeStatic || !m.IsStatic && includeInstance);
}
else if (invocation.Receiver is SimpleNameSyntax && invocation.IsInStaticContext)
{
methodGroup = methodGroup.Where(m => m.IsStatic || m.MethodKind == MethodKind.LocalFunction);
}
foreach (var methodOverload in methodGroup)
{
var signature = BuildSignature(methodOverload);
signaturesSet.Add(signature);
var score = InvocationScore(methodOverload, types);
if (score > bestScore)
{
bestScore = score;
bestScoredItem = signature;
}
}
var signaturesList = signaturesSet.ToList();
response.Signatures = [.. signaturesList];
if(bestScoredItem == null)
{
response.ActiveSignature = -1;
}
else
{
response.ActiveSignature = signaturesList.IndexOf((SignatureInformation)bestScoredItem);
}
return new SignatureHelpResult()
{
Value = response,
};
}
private static async Task<InvocationContext?> GetInvocation(Document document, int line, int column)
{
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(line, column));
var tree = await document.GetSyntaxTreeAsync();
if (tree is null) return null;
var root = await tree.GetRootAsync();
var node = root.FindToken(position).Parent;
// Walk up until we find a node that we're interested in.
while (node != null)
{
if (node is InvocationExpressionSyntax invocation && invocation.ArgumentList.Span.Contains(position))
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel is null ? null : new InvocationContext(semanticModel, position, invocation.Expression, invocation.ArgumentList, invocation.IsInStaticContext());
}
if (node is BaseObjectCreationExpressionSyntax objectCreation && (objectCreation.ArgumentList?.Span.Contains(position) ?? false))
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel is null ? null : new InvocationContext(semanticModel, position, objectCreation, objectCreation.ArgumentList, objectCreation.IsInStaticContext());
}
if (node is AttributeSyntax attributeSyntax && (attributeSyntax.ArgumentList?.Span.Contains(position) ?? false))
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel is null ? null : new InvocationContext(semanticModel, position, attributeSyntax, attributeSyntax.ArgumentList, attributeSyntax.IsInStaticContext());
}
node = node.Parent;
}
return null;
}
private static int InvocationScore(IMethodSymbol symbol, IEnumerable<TypeInfo> types)
{
var parameters = symbol.Parameters;
if (parameters.Length < types.Count())
{
return int.MinValue;
}
var score = 0;
var invocationEnum = types.GetEnumerator();
var definitionEnum = parameters.GetEnumerator();
while (invocationEnum.MoveNext() && definitionEnum.MoveNext())
{
if (invocationEnum.Current.ConvertedType == null)
{
// 1 point for having a parameter
score += 1;
}
else if (SymbolEqualityComparer.Default.Equals(invocationEnum.Current.ConvertedType, definitionEnum.Current.Type))
{
// 2 points for having a parameter and being
// the same type
score += 2;
}
}
return score;
}
private static SignatureInformation BuildSignature(IMethodSymbol symbol)
{
var StructuredDocumentation = DocumentationConverter.GetStructuredDocumentation(symbol);
return new SignatureInformation
{
Documentation = new MarkdownString()
{
Value = StructuredDocumentation?.SummaryText ?? "",
},
Label = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
Parameters = [..symbol.Parameters.Select(parameter => new ParameterInformation()
{
Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
Documentation = new MarkdownString()
{
Value = StructuredDocumentation?.GetParameterText(parameter.Name) ?? string.Empty,
},
})],
ActiveParameter = null,
};
}
}

View File

@@ -0,0 +1,6 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct SignatureHelpResult
{
public SignatureHelp Value { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct SignatureInformation
{
public int? ActiveParameter { get; set; }
public MarkdownString? Documentation { get; set; }
public string Label { get; set; }
public ParameterInformation[] Parameters { get; set; }
}

View File

@@ -0,0 +1,260 @@
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using System.Text;
namespace RobotNet.WebApp.Scripts.Monaco;
public enum MarkdownFormat
{
Default,
Italicize,
FirstLineAsCSharp,
FirstLineDefaultRestCSharp,
AllTextAsCSharp
}
public static class MarkdownHelpers
{
private static readonly Regex EscapeRegex = new("([\\\\`\\*_\\{\\}\\[\\]\\(\\)#+\\-\\.!])", RegexOptions.Compiled);
private const string ContainerStart = "ContainerStart";
private const string ContainerEnd = "ContainerEnd";
public static string Escape(string markdown) => string.IsNullOrEmpty(markdown) ? string.Empty : EscapeRegex.Replace(markdown, "\\$1");
public static void TaggedTextToMarkdown(ImmutableArray<TaggedText> taggedParts, StringBuilder stringBuilder, string newLine, MarkdownFormat markdownFormat, out bool endedWithLineBreak)
{
bool isInCodeBlock = false;
bool brokeLine = true;
bool afterFirstLine = false;
if (markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
int num = 0;
while (num < taggedParts.Length)
{
TaggedText taggedText = taggedParts[num];
bool flag;
if (brokeLine && markdownFormat != MarkdownFormat.Italicize)
{
brokeLine = false;
if (!afterFirstLine)
{
if (markdownFormat != MarkdownFormat.FirstLineAsCSharp)
{
goto IL_00a2;
}
flag = true;
}
else
{
if (markdownFormat != MarkdownFormat.FirstLineDefaultRestCSharp)
{
goto IL_00a2;
}
flag = true;
}
goto IL_00bf;
}
goto IL_0279;
IL_00a2:
flag = markdownFormat == MarkdownFormat.AllTextAsCSharp;
goto IL_00bf;
IL_0279:
switch (taggedText.Tag)
{
case "Text":
if (!isInCodeBlock)
{
addText(taggedText.Text);
break;
}
endBlock();
addText(taggedText.Text);
break;
case "Space":
if (isInCodeBlock)
{
if (indexIsTag(num + 1, ["Text"]))
{
endBlock();
}
addText(taggedText.Text);
break;
}
goto case "Punctuation";
case "Punctuation":
addText(taggedText.Text);
break;
case ContainerStart:
addNewline();
addText(taggedText.Text);
break;
case ContainerEnd:
addNewline();
break;
case "LineBreak":
if (stringBuilder.Length != 0 && !indexIsTag(num + 1, [ContainerStart, ContainerEnd]) && num + 1 != taggedParts.Length)
{
addNewline();
}
break;
default:
if (!isInCodeBlock)
{
isInCodeBlock = true;
stringBuilder.Append('`');
}
stringBuilder.Append(taggedText.Text);
brokeLine = false;
break;
}
num++;
continue;
IL_00bf:
bool flag2 = flag;
if (!flag2)
{
for (int j = num; j < taggedParts.Length; flag2 = true, j++)
{
switch (taggedParts[j].Tag)
{
case "Text":
flag2 = false;
break;
default:
continue;
case ContainerStart:
case ContainerEnd:
case "LineBreak":
break;
}
break;
}
}
else
{
flag2 = !indexIsTag(num,
[
ContainerStart,
ContainerEnd,
"LineBreak"
]);
}
if (flag2)
{
afterFirstLine = true;
stringBuilder.Append("```csharp");
stringBuilder.Append(newLine);
while (true)
{
if (num < taggedParts.Length)
{
taggedText = taggedParts[num];
if (taggedText.Tag == ContainerStart || taggedText.Tag == ContainerEnd || taggedText.Tag == "LineBreak")
{
stringBuilder.Append(newLine);
if (markdownFormat != MarkdownFormat.AllTextAsCSharp && markdownFormat != MarkdownFormat.FirstLineDefaultRestCSharp)
{
break;
}
}
else
{
stringBuilder.Append(taggedText.Text);
}
num++;
continue;
}
stringBuilder.Append(newLine);
stringBuilder.Append("```");
endedWithLineBreak = false;
return;
}
stringBuilder.Append("```");
}
goto IL_0279;
}
if (isInCodeBlock)
{
endBlock();
}
if (!brokeLine && markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
endedWithLineBreak = brokeLine;
void addNewline()
{
if (isInCodeBlock)
{
endBlock();
}
if (markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
stringBuilder.Append(newLine);
stringBuilder.Append(newLine);
brokeLine = true;
if (markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
}
void addText(string text)
{
brokeLine = false;
afterFirstLine = true;
if (!isInCodeBlock)
{
text = Escape(text);
}
stringBuilder.Append(text);
}
void endBlock()
{
stringBuilder.Append('`');
isInCodeBlock = false;
}
bool indexIsTag(int i, string[] tags)
{
if (i < taggedParts.Length)
{
return tags.Contains(taggedParts[i].Tag);
}
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public struct MarkdownString
{
public string Value { get; set; }
public bool? IsTrusted { get; set; } // TODO | MarkdownStringTrustedOptions;
public bool? SupportThemeIcons { get; set; }
public bool? SupportHtml { get; set; }
public UriComponents? BaseUri { get; set; }
public IDictionary<string, UriComponents>? Uris { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public enum MarkerSeverity
{
Hint = 1,
Info = 2,
Warning = 4,
Error = 8,
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public enum MarkerTag
{
Unnecessary = 1,
Deprecated = 2,
}

View File

@@ -0,0 +1,150 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace RobotNet.WebApp.Scripts.Monaco;
public static class MonacoExtensions
{
public static bool IsInStaticContext(this SyntaxNode node)
{
// this/base calls are always static.
if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
{
return true;
}
var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (memberDeclaration == null)
{
return false;
}
switch (memberDeclaration.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
return GetModifiers(memberDeclaration).Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return GetModifiers(memberDeclaration).Any(SyntaxKind.StaticKeyword) ||
node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Inside a field one can only access static members of a type (unless it's top-level).
return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit);
case SyntaxKind.DestructorDeclaration:
return false;
}
// Global statements are not a static context.
if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
{
return false;
}
// any other location is considered static
return true;
}
public static SyntaxTokenList GetModifiers(SyntaxNode member)
{
if (member != null)
{
switch (member.Kind())
{
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)member).Modifiers;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
return ((TypeDeclarationSyntax)member).Modifiers;
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)member).Modifiers;
case SyntaxKind.FieldDeclaration:
return ((FieldDeclarationSyntax)member).Modifiers;
case SyntaxKind.EventFieldDeclaration:
return ((EventFieldDeclarationSyntax)member).Modifiers;
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)member).Modifiers;
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)member).Modifiers;
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)member).Modifiers;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)member).Modifiers;
case SyntaxKind.IndexerDeclaration:
return ((IndexerDeclarationSyntax)member).Modifiers;
case SyntaxKind.OperatorDeclaration:
return ((OperatorDeclarationSyntax)member).Modifiers;
case SyntaxKind.ConversionOperatorDeclaration:
return ((ConversionOperatorDeclarationSyntax)member).Modifiers;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)member).Modifiers;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return ((AccessorDeclarationSyntax)member).Modifiers;
}
}
return default;
}
public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode?> childGetter)
where TParent : SyntaxNode
{
var ancestor = node.GetAncestor<TParent>();
if (ancestor == null)
{
return false;
}
var child = childGetter(ancestor);
// See if node passes through child on the way up to ancestor.
return node.GetAncestorsOrThis<SyntaxNode>().Contains(child);
}
public static TNode? GetAncestor<TNode>(this SyntaxNode node)
where TNode : SyntaxNode
{
var current = node.Parent;
while (current != null)
{
if (current is TNode tNode)
{
return tNode;
}
current = current.GetParent();
}
return null;
}
public static IEnumerable<TNode> GetAncestorsOrThis<TNode>(this SyntaxNode node)
where TNode : SyntaxNode
{
var current = node;
while (current != null)
{
if (current is TNode tNode)
{
yield return tNode;
}
current = current.GetParent();
}
}
private static SyntaxNode? GetParent(this SyntaxNode node)
{
return node is IStructuredTriviaSyntax trivia ? trivia.ParentTrivia.Token.Parent : node.Parent;
}
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public struct Range
{
public int EndColumn { get; set; }
public int EndLineNumber { get; set; }
public int StartColumn { get; set; }
public int StartLineNumber { get; set; }
}

View File

@@ -0,0 +1,16 @@
using Microsoft.CodeAnalysis.QuickInfo;
using System.Text;
namespace RobotNet.WebApp.Scripts.Monaco;
public static class StringBuilderExtension
{
public static void AppendSection(this StringBuilder builder, QuickInfoSection section, MarkdownFormat format, ref bool lastLineBreak)
{
if (!lastLineBreak && section.TaggedParts.Length > 0 && section.TaggedParts[0].Tag != "LineBreak")
{
builder.Append("\n\n");
}
MarkdownHelpers.TaggedTextToMarkdown(section.TaggedParts, builder, "\n", format, out lastLineBreak);
}
}

View File

@@ -0,0 +1,10 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public struct UriComponents
{
public string? Scheme { get; set; }
public string? Authority { get; set; }
public string? Path { get; set; }
public string? Query { get; set; }
public string? Fragment { get; set; }
}