-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
235 lines (195 loc) · 7.09 KB
/
Program.cs
File metadata and controls
235 lines (195 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.IntelliCode.Api.WholeLineCompletion;
using Microsoft.VisualStudio.IntelliCode.WholeLineCompletion.ModelInference;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace IntelliCodeLsp;
class Program
{
// Path to the model
private const string ModelArchivePath =
@"E:\Program Files\Microsoft Visual Studio\18\Community\Common7\IDE\Extensions\Microsoft\IntelliCode\BundledModels\all_line-completion2";
private const string ModelExtractionPath =
@"C:\Users\daniel\AppData\Local\Microsoft\VisualStudio\18.0_f5fd3385\IntelliCodeModels\all_line-completion2_ExtractedData";
private static readonly CodeGenerationConfig Config = new CodeGenerationConfig
{
OutputSeqLength = 20,
EodToken = 1,
BeamSize = 4,
NumberOfResults = 4,
MaxSequenceLength = 256
};
private static readonly Dictionary<string, string> Documents = new();
private static CodeGenerator? _generator;
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
var stdin = new BinaryReader(Console.OpenStandardInput());
var stdout = Console.OpenStandardOutput();
try
{
var ctx = new LocalSystemContext();
_generator = new CodeGenerator(ctx);
_generator.Initialize(ModelArchivePath, ModelExtractionPath, CancellationToken.None);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[IntelliCodeLsp] Model init failed: {ex.Message}");
}
while (true)
{
try
{
string? json = ReadMessage(stdin);
if (json == null) break;
var msg = JsonConvert.DeserializeObject<LspMessage>(json);
if (msg == null) continue;
HandleMessage(msg, stdout);
}
catch (EndOfStreamException)
{
break;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[IntelliCodeLsp] Error: {ex}");
}
}
}
static void HandleMessage(LspMessage msg, Stream stdout)
{
switch (msg.Method)
{
case "initialize":
SendResult(stdout, msg.Id, new InitializeResult());
break;
case "initialized":
break;
case "shutdown":
SendResult(stdout, msg.Id, null);
break;
case "exit":
Environment.Exit(0);
break;
case "textDocument/didOpen":
{
var p = msg.Params!.ToObject<DidOpenTextDocumentParams>()!;
Documents[p.TextDocument.Uri] = p.TextDocument.Text;
break;
}
case "textDocument/didChange":
{
var p = msg.Params!.ToObject<DidChangeTextDocumentParams>()!;
if (p.ContentChanges.Length > 0)
Documents[p.TextDocument.Uri] = p.ContentChanges[^1].Text;
break;
}
case "textDocument/didClose":
{
var p = msg.Params!.ToObject<DidOpenTextDocumentParams>()!;
Documents.Remove(p.TextDocument.Uri);
break;
}
case "textDocument/completion":
{
var p = msg.Params!.ToObject<TextDocumentPositionParams>()!;
var items = GetCompletions(p);
SendResult(stdout, msg.Id, items);
break;
}
default:
break;
}
}
static List<CompletionItem> GetCompletions(TextDocumentPositionParams p)
{
var result = new List<CompletionItem>();
if (_generator == null)
return result;
if (!Documents.TryGetValue(p.TextDocument.Uri, out string? docText))
return result;
string context = ContextExtractor.GetContext(docText, p.Position.Line, p.Position.Character);
if (string.IsNullOrWhiteSpace(context))
return result;
try
{
WholeLineResponse response = _generator.Execute(
new WholeLineRequest { Contexts = new System.Collections.Generic.List<string> { context } },
Config,
CancellationToken.None);
if (response?.Generations == null || response.Generations.Count == 0)
return result;
for (int i = 0; i < response.Generations[0].Count; i++)
{
string[]? tokens = response.Generations[0][i];
if (tokens == null || tokens.Length == 0) continue;
string? text = Denormalizer.Denormalize(tokens);
if (string.IsNullOrEmpty(text)) continue;
float prob = response.LogProbs[0][i].Length > 0
? response.LogProbs[0][i][0]
: 0f;
result.Add(new CompletionItem
{
Label = text,
InsertText = text,
Kind = 1,
Detail = $"IntelliCode ({Math.Exp(prob):P0})",
Documentation = "IntelliCode whole-line completion"
});
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"[IntelliCodeLsp] Inference error: {ex.Message}");
}
return result;
}
static string? ReadMessage(BinaryReader reader)
{
int contentLength = -1;
while (true)
{
string line = ReadLine(reader);
if (line.Length == 0) break;
if (line.StartsWith("Content-Length: ", StringComparison.OrdinalIgnoreCase))
contentLength = int.Parse(line["Content-Length: ".Length..]);
}
if (contentLength < 0) return null;
byte[] body = reader.ReadBytes(contentLength);
return Encoding.UTF8.GetString(body);
}
static string ReadLine(BinaryReader reader)
{
var sb = new StringBuilder();
while (true)
{
byte b = reader.ReadByte();
if (b == '\n') break;
if (b != '\r') sb.Append((char)b);
}
return sb.ToString();
}
static void SendResult(Stream stdout, JToken? id, object? result)
{
var msg = new LspMessage
{
Id = id,
Result = result == null ? JValue.CreateNull() : JToken.FromObject(result)
};
SendMessage(stdout, msg);
}
static void SendMessage(Stream stdout, LspMessage msg)
{
string json = JsonConvert.SerializeObject(msg);
byte[] body = Encoding.UTF8.GetBytes(json);
byte[] header = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n\r\n");
stdout.Write(header, 0, header.Length);
stdout.Write(body, 0, body.Length);
stdout.Flush();
}
}