This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 169
/
Program.cs
248 lines (218 loc) · 9.92 KB
/
Program.cs
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
236
237
238
239
240
241
242
243
244
245
246
247
248
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Reflection;
using CommandLine;
using CommandLine.Text;
using Microsoft.Build.Locator;
namespace Microsoft.Quantum.QsLanguageServer
{
public class Server
{
public class Options
{
// Note: items in one set are mutually exclusive with items from other sets
protected const string ConnectionViaSocket = "connectionViaSocket";
protected const string ConnectionViaPipe = "connectionViaPipe";
protected const string ConnectionViaStdInOut = "connectionViaStdInOut";
[Option(
'l',
"log",
Required = false,
Default = null,
HelpText = "Path to log messages to.")]
public string? LogFile { get; set; }
[Option(
'p',
"port",
Required = true,
SetName = ConnectionViaSocket,
HelpText = "Port to use for TCP/IP connections.")]
public int Port { get; set; }
[Option(
"unnamed",
Required = false,
SetName = ConnectionViaPipe,
HelpText = "Connect via anonymous pipes.")]
internal bool UseAnonymousPipes { get; set; }
[Option(
'w',
"writer",
Required = true,
SetName = ConnectionViaPipe,
HelpText = "Name of handle of the pipe to write to.")]
public string? WriterPipeName { get; set; }
[Option(
'r',
"reader",
Required = true,
SetName = ConnectionViaPipe,
HelpText = "Name of handle of the pipe to read from.")]
public string? ReaderPipeName { get; set; }
[Option(
's',
"stdinout",
Required = true,
SetName = ConnectionViaStdInOut,
HelpText = "Connect via stdin and stdout.")]
public bool UseStdInOut { get; set; }
}
public enum ReturnCode
{
SUCCESS = 0,
MISSING_ARGUMENTS = 1,
INVALID_ARGUMENTS = 2,
MSBUILD_UNINITIALIZED = 3,
CONNECTION_ERROR = 4,
UNEXPECTED_ERROR = 100,
}
private static int LogAndExit(ReturnCode code, string? logFile = null, string? message = null, bool stdout = false)
{
var text = message ?? (
code == ReturnCode.SUCCESS ? "Exiting normally." :
code == ReturnCode.MISSING_ARGUMENTS ? "Missing command line options." :
code == ReturnCode.INVALID_ARGUMENTS ? "Invalid command line arguments. Use --help to see the list of options." :
code == ReturnCode.MSBUILD_UNINITIALIZED ? "Failed to initialize MsBuild." :
code == ReturnCode.CONNECTION_ERROR ? "Failed to connect." :
code == ReturnCode.UNEXPECTED_ERROR ? "Exiting abnormally." : "");
Log(text, logFile, stdout: stdout);
return (int)code;
}
public static string? Version { get; set; } =
typeof(Server).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
?? typeof(Server).Assembly.GetName().Version?.ToString();
public static int Main(string[] args)
{
// We need to set the current directory to the same directory of
// the LanguageServer executable so that it will pick the global.json file
// and force the MSBuildLocator to use .NET Core SDK 6.0
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
var parser = new Parser(parser => parser.HelpWriter = null); // we want our own custom format for the version info
var options = parser.ParseArguments<Options>(args);
return options.MapResult(
(Options opts) => Run(opts),
errs => errs.IsVersion()
? LogAndExit(ReturnCode.SUCCESS, message: Version, stdout: true)
: LogAndExit(ReturnCode.INVALID_ARGUMENTS, message: HelpText.AutoBuild(options)));
}
private static int Run(Options options)
{
if (options == null)
{
return LogAndExit(ReturnCode.MISSING_ARGUMENTS);
}
// In the case where we actually instantiate a server, we need to "configure" the design time build.
// This needs to be done before any MsBuild packages are loaded.
try
{
MSBuildLocator.RegisterDefaults();
}
catch (Exception ex)
{
// Don't exit here, since exiting without establishing a connection will result in a cryptic failure of the extension.
// Instead, we proceed to create a server instance and establish the connection.
// Any errors can then be properly processed via the standard server-client communication as needed.
Log("[ERROR] MsBuildLocator could not register defaults.", options.LogFile);
Log(ex, options.LogFile);
}
QsLanguageServer server;
try
{
server = options.UseStdInOut
? ConnectViaStdInOut(options.LogFile)
: options.ReaderPipeName != null && options.WriterPipeName != null
? ConnectViaPipes(options.WriterPipeName, options.ReaderPipeName, options.UseAnonymousPipes, options.LogFile)
: ConnectViaSocket(port: options.Port, logFile: options.LogFile);
}
catch (Exception ex)
{
Log("[ERROR] Failed to launch server.", options.LogFile);
return LogAndExit(ReturnCode.CONNECTION_ERROR, options.LogFile, ex.ToString());
}
Log("Listening...", options.LogFile);
try
{
_ = server.CheckDotNetSdkVersionAsync();
server.WaitForShutdown();
}
catch (Exception ex)
{
Log("[ERROR] Unexpected error.", options.LogFile);
return LogAndExit(ReturnCode.UNEXPECTED_ERROR, options.LogFile, ex.ToString());
}
return server.ReadyForExit
? LogAndExit(ReturnCode.SUCCESS, options.LogFile)
: LogAndExit(ReturnCode.UNEXPECTED_ERROR, options.LogFile);
}
private static void Log(object msg, string? logFile = null, bool stdout = false)
{
if (logFile != null)
{
using var writer = new StreamWriter(logFile, append: true);
writer.WriteLine(msg);
}
else
{
// Unless we need to explicitly write to stdout (e.g.: for
// version info), write to error in order to prevent confusing
// language server clients.
(stdout ? Console.Out : Console.Error).WriteLine(msg);
}
}
internal static QsLanguageServer ConnectViaStdInOut(string? logFile = null)
{
Log($"Connecting via stdin and stdout.", logFile, stdout: true);
return new QsLanguageServer(Console.OpenStandardOutput(), Console.OpenStandardInput());
}
internal static QsLanguageServer ConnectViaPipes(string writer, string reader, bool useAnonymousPipes, string? logFile = null) =>
useAnonymousPipes
? ConnectViaAnonymousPipes(writer, reader, logFile)
: ConnectViaNamedPipes(writer, reader, logFile);
internal static QsLanguageServer ConnectViaNamedPipes(string writerName, string readerName, string? logFile = null)
{
Log($"Connecting via named pipe. {Environment.NewLine}ReaderPipe: \"{readerName}\" {Environment.NewLine}WriterPipe: \"{writerName}\"", logFile, stdout: true);
var writerPipe = new NamedPipeClientStream(writerName);
var readerPipe = new NamedPipeClientStream(readerName);
readerPipe.Connect(30000);
if (!readerPipe.IsConnected)
{
Log($"[ERROR] Connection attempted timed out.", logFile);
}
writerPipe.Connect(30000);
if (!writerPipe.IsConnected)
{
Log($"[ERROR] Connection attempted timed out.", logFile);
}
return new QsLanguageServer(writerPipe, readerPipe);
}
internal static QsLanguageServer ConnectViaAnonymousPipes(string writerHandle, string readerHandle, string? logFile = null)
{
Log($"Connecting via anonymous pipe.", logFile, stdout: true);
var writerPipe = new AnonymousPipeClientStream(PipeDirection.Out, writerHandle);
var readerPipe = new AnonymousPipeClientStream(PipeDirection.In, readerHandle);
if (!writerPipe.IsConnected || !readerPipe.IsConnected)
{
Log($"[ERROR] Connection failed.", logFile);
}
return new QsLanguageServer(writerPipe, readerPipe);
}
internal static QsLanguageServer ConnectViaSocket(string hostname = "localhost", int port = 8008, string? logFile = null)
{
Log($"Connecting via socket. {Environment.NewLine}Port number: {port}", logFile, stdout: true);
Stream? stream = null;
try
{
stream = new TcpClient(hostname, port).GetStream();
}
catch (Exception ex)
{
Log("[ERROR] Failed to get network stream.", logFile);
Log(ex.ToString(), logFile);
}
return new QsLanguageServer(stream, stream);
}
}
}