HipcGenerator.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. using Microsoft.CodeAnalysis;
  2. using Microsoft.CodeAnalysis.CSharp;
  3. using Microsoft.CodeAnalysis.CSharp.Syntax;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. namespace Ryujinx.Horizon.Generators.Hipc
  7. {
  8. [Generator]
  9. class HipcGenerator : ISourceGenerator
  10. {
  11. private const string ArgVariablePrefix = "arg";
  12. private const string ResultVariableName = "result";
  13. private const string IsBufferMapAliasVariableName = "isBufferMapAlias";
  14. private const string InObjectsVariableName = "inObjects";
  15. private const string OutObjectsVariableName = "outObjects";
  16. private const string ResponseVariableName = "response";
  17. private const string OutRawDataVariableName = "outRawData";
  18. private const string TypeSystemReadOnlySpan = "System.ReadOnlySpan";
  19. private const string TypeSystemSpan = "System.Span";
  20. private const string TypeStructLayoutAttribute = "System.Runtime.InteropServices.StructLayoutAttribute";
  21. public const string CommandAttributeName = "CmifCommandAttribute";
  22. private const string TypeResult = "Ryujinx.Horizon.Common.Result";
  23. private const string TypeBufferAttribute = "Ryujinx.Horizon.Sdk.Sf.BufferAttribute";
  24. private const string TypeCopyHandleAttribute = "Ryujinx.Horizon.Sdk.Sf.CopyHandleAttribute";
  25. private const string TypeMoveHandleAttribute = "Ryujinx.Horizon.Sdk.Sf.MoveHandleAttribute";
  26. private const string TypeClientProcessIdAttribute = "Ryujinx.Horizon.Sdk.Sf.ClientProcessIdAttribute";
  27. private const string TypeCommandAttribute = "Ryujinx.Horizon.Sdk.Sf." + CommandAttributeName;
  28. private const string TypeIServiceObject = "Ryujinx.Horizon.Sdk.Sf.IServiceObject";
  29. private enum Modifier
  30. {
  31. None,
  32. Ref,
  33. Out,
  34. In
  35. }
  36. private struct OutParameter
  37. {
  38. public readonly string Name;
  39. public readonly string TypeName;
  40. public readonly int Index;
  41. public readonly CommandArgType Type;
  42. public OutParameter(string name, string typeName, int index, CommandArgType type)
  43. {
  44. Name = name;
  45. TypeName = typeName;
  46. Index = index;
  47. Type = type;
  48. }
  49. }
  50. public void Execute(GeneratorExecutionContext context)
  51. {
  52. HipcSyntaxReceiver syntaxReceiver = (HipcSyntaxReceiver)context.SyntaxReceiver;
  53. foreach (var commandInterface in syntaxReceiver.CommandInterfaces)
  54. {
  55. if (!NeedsIServiceObjectImplementation(context.Compilation, commandInterface.ClassDeclarationSyntax))
  56. {
  57. continue;
  58. }
  59. CodeGenerator generator = new CodeGenerator();
  60. string className = commandInterface.ClassDeclarationSyntax.Identifier.ToString();
  61. generator.AppendLine("using Ryujinx.Horizon.Common;");
  62. generator.AppendLine("using Ryujinx.Horizon.Sdk.Sf;");
  63. generator.AppendLine("using Ryujinx.Horizon.Sdk.Sf.Cmif;");
  64. generator.AppendLine("using Ryujinx.Horizon.Sdk.Sf.Hipc;");
  65. generator.AppendLine("using System;");
  66. generator.AppendLine("using System.Collections.Generic;");
  67. generator.AppendLine("using System.Runtime.CompilerServices;");
  68. generator.AppendLine("using System.Runtime.InteropServices;");
  69. generator.AppendLine();
  70. generator.EnterScope($"namespace {GetNamespaceName(commandInterface.ClassDeclarationSyntax)}");
  71. generator.EnterScope($"partial class {className}");
  72. GenerateMethodTable(generator, context.Compilation, commandInterface);
  73. foreach (var method in commandInterface.CommandImplementations)
  74. {
  75. generator.AppendLine();
  76. GenerateMethod(generator, context.Compilation, method);
  77. }
  78. generator.LeaveScope();
  79. generator.LeaveScope();
  80. context.AddSource($"{className}.g.cs", generator.ToString());
  81. }
  82. }
  83. private static string GetNamespaceName(SyntaxNode syntaxNode)
  84. {
  85. while (syntaxNode != null && !(syntaxNode is NamespaceDeclarationSyntax))
  86. {
  87. syntaxNode = syntaxNode.Parent;
  88. }
  89. if (syntaxNode == null)
  90. {
  91. return string.Empty;
  92. }
  93. return ((NamespaceDeclarationSyntax)syntaxNode).Name.ToString();
  94. }
  95. private static void GenerateMethodTable(CodeGenerator generator, Compilation compilation, CommandInterface commandInterface)
  96. {
  97. generator.EnterScope($"public IReadOnlyDictionary<int, CommandHandler> GetCommandHandlers()");
  98. generator.EnterScope($"return new Dictionary<int, CommandHandler>()");
  99. foreach (var method in commandInterface.CommandImplementations)
  100. {
  101. foreach (var commandId in GetAttributeAguments(compilation, method, TypeCommandAttribute, 0))
  102. {
  103. string[] args = new string[method.ParameterList.Parameters.Count];
  104. int index = 0;
  105. foreach (var parameter in method.ParameterList.Parameters)
  106. {
  107. string canonicalTypeName = GetCanonicalTypeNameWithGenericArguments(compilation, parameter.Type);
  108. CommandArgType argType = GetCommandArgType(compilation, parameter);
  109. string arg;
  110. if (argType == CommandArgType.Buffer)
  111. {
  112. string bufferFlags = GetFirstAttributeAgument(compilation, parameter, TypeBufferAttribute, 0);
  113. string bufferFixedSize = GetFirstAttributeAgument(compilation, parameter, TypeBufferAttribute, 1);
  114. if (bufferFixedSize != null)
  115. {
  116. arg = $"new CommandArg({bufferFlags}, {bufferFixedSize})";
  117. }
  118. else
  119. {
  120. arg = $"new CommandArg({bufferFlags})";
  121. }
  122. }
  123. else if (argType == CommandArgType.InArgument || argType == CommandArgType.OutArgument)
  124. {
  125. string alignment = GetTypeAlignmentExpression(compilation, parameter.Type);
  126. arg = $"new CommandArg(CommandArgType.{argType}, Unsafe.SizeOf<{canonicalTypeName}>(), {alignment})";
  127. }
  128. else
  129. {
  130. arg = $"new CommandArg(CommandArgType.{argType})";
  131. }
  132. args[index++] = arg;
  133. }
  134. generator.AppendLine($"{{ {commandId}, new CommandHandler({method.Identifier.Text}, {string.Join(", ", args)}) }},");
  135. }
  136. }
  137. generator.LeaveScope(";");
  138. generator.LeaveScope();
  139. }
  140. private static IEnumerable<string> GetAttributeAguments(Compilation compilation, SyntaxNode syntaxNode, string attributeName, int argIndex)
  141. {
  142. ISymbol symbol = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetDeclaredSymbol(syntaxNode);
  143. foreach (var attribute in symbol.GetAttributes())
  144. {
  145. if (attribute.AttributeClass.ToDisplayString() == attributeName && (uint)argIndex < (uint)attribute.ConstructorArguments.Length)
  146. {
  147. yield return attribute.ConstructorArguments[argIndex].ToCSharpString();
  148. }
  149. }
  150. }
  151. private static string GetFirstAttributeAgument(Compilation compilation, SyntaxNode syntaxNode, string attributeName, int argIndex)
  152. {
  153. return GetAttributeAguments(compilation, syntaxNode, attributeName, argIndex).FirstOrDefault();
  154. }
  155. private static void GenerateMethod(CodeGenerator generator, Compilation compilation, MethodDeclarationSyntax method)
  156. {
  157. int inObjectsCount = 0;
  158. int outObjectsCount = 0;
  159. int buffersCount = 0;
  160. foreach (var parameter in method.ParameterList.Parameters)
  161. {
  162. if (IsObject(compilation, parameter))
  163. {
  164. if (IsIn(parameter))
  165. {
  166. inObjectsCount++;
  167. }
  168. else
  169. {
  170. outObjectsCount++;
  171. }
  172. }
  173. else if (IsBuffer(compilation, parameter))
  174. {
  175. buffersCount++;
  176. }
  177. }
  178. generator.EnterScope($"private Result {method.Identifier.Text}(" +
  179. "ref ServiceDispatchContext context, " +
  180. "HipcCommandProcessor processor, " +
  181. "ServerMessageRuntimeMetadata runtimeMetadata, " +
  182. "ReadOnlySpan<byte> inRawData, " +
  183. "ref Span<CmifOutHeader> outHeader)");
  184. bool returnsResult = method.ReturnType != null && GetCanonicalTypeName(compilation, method.ReturnType) == TypeResult;
  185. if (returnsResult || buffersCount != 0 || inObjectsCount != 0)
  186. {
  187. generator.AppendLine($"Result {ResultVariableName};");
  188. if (buffersCount != 0)
  189. {
  190. generator.AppendLine($"bool[] {IsBufferMapAliasVariableName} = new bool[{method.ParameterList.Parameters.Count}];");
  191. generator.AppendLine();
  192. generator.AppendLine($"{ResultVariableName} = processor.ProcessBuffers(ref context, {IsBufferMapAliasVariableName}, runtimeMetadata);");
  193. generator.EnterScope($"if ({ResultVariableName}.IsFailure)");
  194. generator.AppendLine($"return {ResultVariableName};");
  195. generator.LeaveScope();
  196. }
  197. generator.AppendLine();
  198. }
  199. List<OutParameter> outParameters = new List<OutParameter>();
  200. string[] args = new string[method.ParameterList.Parameters.Count];
  201. if (inObjectsCount != 0)
  202. {
  203. generator.AppendLine($"var {InObjectsVariableName} = new IServiceObject[{inObjectsCount}];");
  204. generator.AppendLine();
  205. generator.AppendLine($"{ResultVariableName} = processor.GetInObjects(context.Processor, {InObjectsVariableName});");
  206. generator.EnterScope($"if ({ResultVariableName}.IsFailure)");
  207. generator.AppendLine($"return {ResultVariableName};");
  208. generator.LeaveScope();
  209. generator.AppendLine();
  210. }
  211. if (outObjectsCount != 0)
  212. {
  213. generator.AppendLine($"var {OutObjectsVariableName} = new IServiceObject[{outObjectsCount}];");
  214. }
  215. int index = 0;
  216. int inCopyHandleIndex = 0;
  217. int inMoveHandleIndex = 0;
  218. int inObjectIndex = 0;
  219. foreach (var parameter in method.ParameterList.Parameters)
  220. {
  221. string name = parameter.Identifier.Text;
  222. string argName = GetPrefixedArgName(name);
  223. string canonicalTypeName = GetCanonicalTypeNameWithGenericArguments(compilation, parameter.Type);
  224. CommandArgType argType = GetCommandArgType(compilation, parameter);
  225. Modifier modifier = GetModifier(parameter);
  226. bool isNonSpanBuffer = false;
  227. if (modifier == Modifier.Out)
  228. {
  229. if (IsNonSpanOutBuffer(compilation, parameter))
  230. {
  231. generator.AppendLine($"using var {argName} = CommandSerialization.GetWritableRegion(processor.GetBufferRange({index}));");
  232. argName = $"out {GenerateSpanCastElement0(canonicalTypeName, $"{argName}.Memory.Span")}";
  233. }
  234. else
  235. {
  236. outParameters.Add(new OutParameter(argName, canonicalTypeName, index, argType));
  237. argName = $"out {canonicalTypeName} {argName}";
  238. }
  239. }
  240. else
  241. {
  242. string value = $"default({canonicalTypeName})";
  243. switch (argType)
  244. {
  245. case CommandArgType.InArgument:
  246. value = $"CommandSerialization.DeserializeArg<{canonicalTypeName}>(inRawData, processor.GetInArgOffset({index}))";
  247. break;
  248. case CommandArgType.InCopyHandle:
  249. value = $"CommandSerialization.DeserializeCopyHandle(ref context, {inCopyHandleIndex++})";
  250. break;
  251. case CommandArgType.InMoveHandle:
  252. value = $"CommandSerialization.DeserializeMoveHandle(ref context, {inMoveHandleIndex++})";
  253. break;
  254. case CommandArgType.ProcessId:
  255. value = "CommandSerialization.DeserializeClientProcessId(ref context)";
  256. break;
  257. case CommandArgType.InObject:
  258. value = $"{InObjectsVariableName}[{inObjectIndex++}]";
  259. break;
  260. case CommandArgType.Buffer:
  261. if (IsReadOnlySpan(compilation, parameter))
  262. {
  263. string spanGenericTypeName = GetCanonicalTypeNameOfGenericArgument(compilation, parameter.Type, 0);
  264. value = GenerateSpanCast(spanGenericTypeName, $"CommandSerialization.GetReadOnlySpan(processor.GetBufferRange({index}))");
  265. }
  266. else if (IsSpan(compilation, parameter))
  267. {
  268. value = $"CommandSerialization.GetWritableRegion(processor.GetBufferRange({index}))";
  269. }
  270. else
  271. {
  272. value = $"CommandSerialization.GetRef<{canonicalTypeName}>(processor.GetBufferRange({index}))";
  273. isNonSpanBuffer = true;
  274. }
  275. break;
  276. }
  277. if (IsSpan(compilation, parameter))
  278. {
  279. generator.AppendLine($"using var {argName} = {value};");
  280. string spanGenericTypeName = GetCanonicalTypeNameOfGenericArgument(compilation, parameter.Type, 0);
  281. argName = GenerateSpanCast(spanGenericTypeName, $"{argName}.Memory.Span"); ;
  282. }
  283. else if (isNonSpanBuffer)
  284. {
  285. generator.AppendLine($"ref var {argName} = ref {value};");
  286. }
  287. else if (argType == CommandArgType.InObject)
  288. {
  289. generator.EnterScope($"if (!({value} is {canonicalTypeName} {argName}))");
  290. generator.AppendLine("return SfResult.InvalidInObject;");
  291. generator.LeaveScope();
  292. }
  293. else
  294. {
  295. generator.AppendLine($"var {argName} = {value};");
  296. }
  297. }
  298. if (modifier == Modifier.Ref)
  299. {
  300. argName = $"ref {argName}";
  301. }
  302. else if (modifier == Modifier.In)
  303. {
  304. argName = $"in {argName}";
  305. }
  306. args[index++] = argName;
  307. }
  308. if (args.Length - outParameters.Count > 0)
  309. {
  310. generator.AppendLine();
  311. }
  312. if (returnsResult)
  313. {
  314. generator.AppendLine($"{ResultVariableName} = {method.Identifier.Text}({string.Join(", ", args)});");
  315. generator.AppendLine();
  316. generator.AppendLine($"Span<byte> {OutRawDataVariableName};");
  317. generator.AppendLine();
  318. generator.EnterScope($"if ({ResultVariableName}.IsFailure)");
  319. generator.AppendLine($"context.Processor.PrepareForErrorReply(ref context, out {OutRawDataVariableName}, runtimeMetadata);");
  320. generator.AppendLine($"CommandHandler.GetCmifOutHeaderPointer(ref outHeader, ref {OutRawDataVariableName});");
  321. generator.AppendLine($"return {ResultVariableName};");
  322. generator.LeaveScope();
  323. }
  324. else
  325. {
  326. generator.AppendLine($"{method.Identifier.Text}({string.Join(", ", args)});");
  327. generator.AppendLine();
  328. generator.AppendLine($"Span<byte> {OutRawDataVariableName};");
  329. }
  330. generator.AppendLine();
  331. generator.AppendLine($"var {ResponseVariableName} = context.Processor.PrepareForReply(ref context, out {OutRawDataVariableName}, runtimeMetadata);");
  332. generator.AppendLine($"CommandHandler.GetCmifOutHeaderPointer(ref outHeader, ref {OutRawDataVariableName});");
  333. generator.AppendLine();
  334. generator.EnterScope($"if ({OutRawDataVariableName}.Length < processor.OutRawDataSize)");
  335. generator.AppendLine("return SfResult.InvalidOutRawSize;");
  336. generator.LeaveScope();
  337. if (outParameters.Count != 0)
  338. {
  339. generator.AppendLine();
  340. int outCopyHandleIndex = 0;
  341. int outMoveHandleIndex = outObjectsCount;
  342. int outObjectIndex = 0;
  343. for (int outIndex = 0; outIndex < outParameters.Count; outIndex++)
  344. {
  345. OutParameter outParameter = outParameters[outIndex];
  346. switch (outParameter.Type)
  347. {
  348. case CommandArgType.OutArgument:
  349. generator.AppendLine($"CommandSerialization.SerializeArg<{outParameter.TypeName}>({OutRawDataVariableName}, processor.GetOutArgOffset({outParameter.Index}), {outParameter.Name});");
  350. break;
  351. case CommandArgType.OutCopyHandle:
  352. generator.AppendLine($"CommandSerialization.SerializeCopyHandle({ResponseVariableName}, {outCopyHandleIndex++}, {outParameter.Name});");
  353. break;
  354. case CommandArgType.OutMoveHandle:
  355. generator.AppendLine($"CommandSerialization.SerializeMoveHandle({ResponseVariableName}, {outMoveHandleIndex++}, {outParameter.Name});");
  356. break;
  357. case CommandArgType.OutObject:
  358. generator.AppendLine($"{OutObjectsVariableName}[{outObjectIndex++}] = {outParameter.Name};");
  359. break;
  360. }
  361. }
  362. }
  363. generator.AppendLine();
  364. if (outObjectsCount != 0 || buffersCount != 0)
  365. {
  366. if (outObjectsCount != 0)
  367. {
  368. generator.AppendLine($"processor.SetOutObjects(ref context, {ResponseVariableName}, {OutObjectsVariableName});");
  369. }
  370. if (buffersCount != 0)
  371. {
  372. generator.AppendLine($"processor.SetOutBuffers({ResponseVariableName}, {IsBufferMapAliasVariableName});");
  373. }
  374. generator.AppendLine();
  375. }
  376. generator.AppendLine("return Result.Success;");
  377. generator.LeaveScope();
  378. }
  379. private static string GetPrefixedArgName(string name)
  380. {
  381. return ArgVariablePrefix + name[0].ToString().ToUpperInvariant() + name.Substring(1);
  382. }
  383. private static string GetCanonicalTypeNameOfGenericArgument(Compilation compilation, SyntaxNode syntaxNode, int argIndex)
  384. {
  385. if (syntaxNode is GenericNameSyntax genericNameSyntax)
  386. {
  387. if ((uint)argIndex < (uint)genericNameSyntax.TypeArgumentList.Arguments.Count)
  388. {
  389. return GetCanonicalTypeNameWithGenericArguments(compilation, genericNameSyntax.TypeArgumentList.Arguments[argIndex]);
  390. }
  391. }
  392. return GetCanonicalTypeName(compilation, syntaxNode);
  393. }
  394. private static string GetCanonicalTypeNameWithGenericArguments(Compilation compilation, SyntaxNode syntaxNode)
  395. {
  396. TypeInfo typeInfo = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode);
  397. return typeInfo.Type.ToDisplayString();
  398. }
  399. private static string GetCanonicalTypeName(Compilation compilation, SyntaxNode syntaxNode)
  400. {
  401. TypeInfo typeInfo = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode);
  402. string typeName = typeInfo.Type.ToDisplayString();
  403. int genericArgsStartIndex = typeName.IndexOf('<');
  404. if (genericArgsStartIndex >= 0)
  405. {
  406. return typeName.Substring(0, genericArgsStartIndex);
  407. }
  408. return typeName;
  409. }
  410. private static SpecialType GetSpecialTypeName(Compilation compilation, SyntaxNode syntaxNode)
  411. {
  412. TypeInfo typeInfo = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode);
  413. return typeInfo.Type.SpecialType;
  414. }
  415. private static string GetTypeAlignmentExpression(Compilation compilation, SyntaxNode syntaxNode)
  416. {
  417. TypeInfo typeInfo = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode);
  418. // Since there's no way to get the alignment for a arbitrary type here, let's assume that all
  419. // "special" types are primitive types aligned to their own length.
  420. // Otherwise, assume that the type is a custom struct, that either defines an explicit alignment
  421. // or has an alignment of 1 which is the lowest possible value.
  422. if (typeInfo.Type.SpecialType == SpecialType.None)
  423. {
  424. string pack = GetTypeFirstNamedAttributeAgument(compilation, syntaxNode, TypeStructLayoutAttribute, "Pack");
  425. return pack ?? "1";
  426. }
  427. else
  428. {
  429. return $"Unsafe.SizeOf<{typeInfo.Type.ToDisplayString()}>()";
  430. }
  431. }
  432. private static string GetTypeFirstNamedAttributeAgument(Compilation compilation, SyntaxNode syntaxNode, string attributeName, string argName)
  433. {
  434. ISymbol symbol = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode).Type;
  435. foreach (var attribute in symbol.GetAttributes())
  436. {
  437. if (attribute.AttributeClass.ToDisplayString() == attributeName)
  438. {
  439. foreach (var kv in attribute.NamedArguments)
  440. {
  441. if (kv.Key == argName)
  442. {
  443. return kv.Value.ToCSharpString();
  444. }
  445. }
  446. }
  447. }
  448. return null;
  449. }
  450. private static CommandArgType GetCommandArgType(Compilation compilation, ParameterSyntax parameter)
  451. {
  452. CommandArgType type = CommandArgType.Invalid;
  453. if (IsIn(parameter))
  454. {
  455. if (IsArgument(compilation, parameter))
  456. {
  457. type = CommandArgType.InArgument;
  458. }
  459. else if (IsBuffer(compilation, parameter))
  460. {
  461. type = CommandArgType.Buffer;
  462. }
  463. else if (IsCopyHandle(compilation, parameter))
  464. {
  465. type = CommandArgType.InCopyHandle;
  466. }
  467. else if (IsMoveHandle(compilation, parameter))
  468. {
  469. type = CommandArgType.InMoveHandle;
  470. }
  471. else if (IsObject(compilation, parameter))
  472. {
  473. type = CommandArgType.InObject;
  474. }
  475. else if (IsProcessId(compilation, parameter))
  476. {
  477. type = CommandArgType.ProcessId;
  478. }
  479. }
  480. else if (IsOut(parameter))
  481. {
  482. if (IsArgument(compilation, parameter))
  483. {
  484. type = CommandArgType.OutArgument;
  485. }
  486. else if (IsNonSpanOutBuffer(compilation, parameter))
  487. {
  488. type = CommandArgType.Buffer;
  489. }
  490. else if (IsCopyHandle(compilation, parameter))
  491. {
  492. type = CommandArgType.OutCopyHandle;
  493. }
  494. else if (IsMoveHandle(compilation, parameter))
  495. {
  496. type = CommandArgType.OutMoveHandle;
  497. }
  498. else if (IsObject(compilation, parameter))
  499. {
  500. type = CommandArgType.OutObject;
  501. }
  502. }
  503. return type;
  504. }
  505. private static bool IsArgument(Compilation compilation,ParameterSyntax parameter)
  506. {
  507. return !IsBuffer(compilation, parameter) &&
  508. !IsHandle(compilation, parameter) &&
  509. !IsObject(compilation, parameter) &&
  510. !IsProcessId(compilation, parameter) &&
  511. IsUnmanagedType(compilation, parameter.Type);
  512. }
  513. private static bool IsBuffer(Compilation compilation, ParameterSyntax parameter)
  514. {
  515. return HasAttribute(compilation, parameter, TypeBufferAttribute) &&
  516. IsValidTypeForBuffer(compilation, parameter);
  517. }
  518. private static bool IsNonSpanOutBuffer(Compilation compilation, ParameterSyntax parameter)
  519. {
  520. return HasAttribute(compilation, parameter, TypeBufferAttribute) &&
  521. IsUnmanagedType(compilation, parameter.Type);
  522. }
  523. private static bool IsValidTypeForBuffer(Compilation compilation, ParameterSyntax parameter)
  524. {
  525. return IsReadOnlySpan(compilation, parameter) ||
  526. IsSpan(compilation, parameter) ||
  527. IsUnmanagedType(compilation, parameter.Type);
  528. }
  529. private static bool IsUnmanagedType(Compilation compilation, SyntaxNode syntaxNode)
  530. {
  531. TypeInfo typeInfo = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode);
  532. return typeInfo.Type.IsUnmanagedType;
  533. }
  534. private static bool IsReadOnlySpan(Compilation compilation, ParameterSyntax parameter)
  535. {
  536. return GetCanonicalTypeName(compilation, parameter.Type) == TypeSystemReadOnlySpan;
  537. }
  538. private static bool IsSpan(Compilation compilation, ParameterSyntax parameter)
  539. {
  540. return GetCanonicalTypeName(compilation, parameter.Type) == TypeSystemSpan;
  541. }
  542. private static bool IsHandle(Compilation compilation, ParameterSyntax parameter)
  543. {
  544. return IsCopyHandle(compilation, parameter) || IsMoveHandle(compilation, parameter);
  545. }
  546. private static bool IsCopyHandle(Compilation compilation, ParameterSyntax parameter)
  547. {
  548. return HasAttribute(compilation, parameter, TypeCopyHandleAttribute) &&
  549. GetSpecialTypeName(compilation, parameter.Type) == SpecialType.System_Int32;
  550. }
  551. private static bool IsMoveHandle(Compilation compilation, ParameterSyntax parameter)
  552. {
  553. return HasAttribute(compilation, parameter, TypeMoveHandleAttribute) &&
  554. GetSpecialTypeName(compilation, parameter.Type) == SpecialType.System_Int32;
  555. }
  556. private static bool IsObject(Compilation compilation, ParameterSyntax parameter)
  557. {
  558. SyntaxNode syntaxNode = parameter.Type;
  559. TypeInfo typeInfo = compilation.GetSemanticModel(syntaxNode.SyntaxTree).GetTypeInfo(syntaxNode);
  560. return typeInfo.Type.ToDisplayString() == TypeIServiceObject ||
  561. typeInfo.Type.AllInterfaces.Any(x => x.ToDisplayString() == TypeIServiceObject);
  562. }
  563. private static bool IsProcessId(Compilation compilation, ParameterSyntax parameter)
  564. {
  565. return HasAttribute(compilation, parameter, TypeClientProcessIdAttribute) &&
  566. GetSpecialTypeName(compilation, parameter.Type) == SpecialType.System_UInt64;
  567. }
  568. private static bool IsIn(ParameterSyntax parameter)
  569. {
  570. return !IsOut(parameter);
  571. }
  572. private static bool IsOut(ParameterSyntax parameter)
  573. {
  574. return parameter.Modifiers.Any(SyntaxKind.OutKeyword);
  575. }
  576. private static Modifier GetModifier(ParameterSyntax parameter)
  577. {
  578. foreach (SyntaxToken syntaxToken in parameter.Modifiers)
  579. {
  580. if (syntaxToken.IsKind(SyntaxKind.RefKeyword))
  581. {
  582. return Modifier.Ref;
  583. }
  584. else if (syntaxToken.IsKind(SyntaxKind.OutKeyword))
  585. {
  586. return Modifier.Out;
  587. }
  588. else if (syntaxToken.IsKind(SyntaxKind.InKeyword))
  589. {
  590. return Modifier.In;
  591. }
  592. }
  593. return Modifier.None;
  594. }
  595. private static string GenerateSpanCastElement0(string targetType, string input)
  596. {
  597. return $"{GenerateSpanCast(targetType, input)}[0]";
  598. }
  599. private static string GenerateSpanCast(string targetType, string input)
  600. {
  601. return $"MemoryMarshal.Cast<byte, {targetType}>({input})";
  602. }
  603. private static bool HasAttribute(Compilation compilation, ParameterSyntax parameterSyntax, string fullAttributeName)
  604. {
  605. foreach (var attributeList in parameterSyntax.AttributeLists)
  606. {
  607. foreach (var attribute in attributeList.Attributes)
  608. {
  609. if (GetCanonicalTypeName(compilation, attribute) == fullAttributeName)
  610. {
  611. return true;
  612. }
  613. }
  614. }
  615. return false;
  616. }
  617. private static bool NeedsIServiceObjectImplementation(Compilation compilation, ClassDeclarationSyntax classDeclarationSyntax)
  618. {
  619. ITypeSymbol type = compilation.GetSemanticModel(classDeclarationSyntax.SyntaxTree).GetDeclaredSymbol(classDeclarationSyntax);
  620. var serviceObjectInterface = type.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == TypeIServiceObject);
  621. var interfaceMember = serviceObjectInterface?.GetMembers().FirstOrDefault(x => x.Name == "GetCommandHandlers");
  622. // Return true only if the class implements IServiceObject but does not actually implement the method
  623. // that the interface defines, since this is the only case we want to handle, if the method already exists
  624. // we have nothing to do.
  625. return serviceObjectInterface != null && type.FindImplementationForInterfaceMember(interfaceMember) == null;
  626. }
  627. public void Initialize(GeneratorInitializationContext context)
  628. {
  629. context.RegisterForSyntaxNotifications(() => new HipcSyntaxReceiver());
  630. }
  631. }
  632. }