Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add godbolt command #1027

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/Modix.Bot/Modules/GodboltDisasmModal.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#nullable enable
using Discord;
using Discord.Interactions;

namespace Modix.Bot.Modules
{
public class GodboltDisasmModal : IModal
{
private string _language = "csharp";

public string Title => "Godbolt";

[InputLabel("Code")]
[ModalTextInput("code", TextInputStyle.Paragraph, initValue: """
using System;

class Program
{
static int Square(int num) => num * num;
static void Main() => Console.WriteLine(Square(42));
}
""")]
public required string Code { get; set; }

[InputLabel("Language: csharp, fsharp, vb or il")]
[ModalTextInput("language", initValue: "csharp")]
[RequiredInput(true)]
public required string Language
{
get => _language;
set => _language = value.ToLowerInvariant();
}

[InputLabel("Arguments")]
[ModalTextInput("arguments", TextInputStyle.Short)]
[RequiredInput(false)]
public string Arguments { get; set; } = "";
}
}
56 changes: 56 additions & 0 deletions src/Modix.Bot/Modules/GodboltModule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#nullable enable
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Interactions;
using Modix.Bot.Attributes;
using Modix.Services.CommandHelp;
using Modix.Services.Godbolt;

namespace Modix.Bot.Modules
{
[ModuleHelp("Godbolt", "Commands for working with Godbolt.")]
public class GodboltModule : InteractionModuleBase
{
private readonly GodboltService _godboltService;

public GodboltModule(GodboltService godboltService)
{
_godboltService = godboltService;
}

[SlashCommand("godbolt", description: "Compile and disassemble JIT code.")]
[DoNotDefer]
public Task DisasmAsync() => Context.Interaction.RespondWithModalAsync<GodboltDisasmModal>("godbolt_disasm");

[ModalInteraction("godbolt_disasm")]
public async Task ProcessDisasmAsync(GodboltDisasmModal modal)
{
try
{
var response = $"""
```{modal.Language}
{modal.Code}
```
Disassembly{(string.IsNullOrWhiteSpace(modal.Arguments) ? "" : $" with ``{modal.Arguments}``")}:
```
{await _godboltService.CompileAsync(modal.Code, modal.Language, modal.Arguments)}
```
""";

if (response.Length > DiscordConfig.MaxMessageSize)
{
await FollowupAsync("Error: The code is too long to be converted to a message.", allowedMentions: AllowedMentions.None);
return;
}

await FollowupAsync(response, allowedMentions: AllowedMentions.None);
}
catch (Exception ex)
{
await FollowupAsync($"Error: {ex}", allowedMentions: AllowedMentions.None);
return;
}
}
}
}
15 changes: 15 additions & 0 deletions src/Modix.Services/Godbolt/AssemblyFilters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#nullable enable
namespace Modix.Services.Godbolt
{
internal record class AssemblyFilters
{
public bool Binary { get; set; } = false;
public bool CommentOnly { get; set; } = true;
public bool Directives { get; set; } = true;
public bool Labels { get; set; } = true;
public bool Trim { get; set; } = true;
public bool Demangle { get; set; } = true;
public bool Intel { get; set; } = true;
public bool Execute { get; set; } = false;
}
}
9 changes: 9 additions & 0 deletions src/Modix.Services/Godbolt/CompileRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#nullable enable
namespace Modix.Services.Godbolt
{
internal record class CompileRequest(string Lang, string Source)
{
public string Compiler { get; } = $"dotnettrunk{Lang}coreclr";
public CompilerOptions Options { get; } = new();
}
}
9 changes: 9 additions & 0 deletions src/Modix.Services/Godbolt/CompilerOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#nullable enable
namespace Modix.Services.Godbolt
{
internal record class CompilerOptions
{
public string UserArguments { get; set; } = "";
public AssemblyFilters Filters { get; } = new();
}
}
45 changes: 45 additions & 0 deletions src/Modix.Services/Godbolt/GodboltService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#nullable enable
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Modix.Services.Godbolt
{
public class GodboltService
{
private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
private const string GodboltApiScheme = "https://godbolt.org/api/compiler/dotnettrunk{0}coreclr/compile";

public GodboltService(IHttpClientFactory httpClientFactory)
{
HttpClientFactory = httpClientFactory;
}

public async Task<string> CompileAsync(string code, string lang, string arguments)
{
var request = new CompileRequest(lang, code);

if (!string.IsNullOrWhiteSpace(arguments))
{
request.Options.UserArguments = arguments;
}

var requestJson = JsonSerializer.Serialize(request, _jsonOptions);

var client = HttpClientFactory.CreateClient();
client.DefaultRequestHeaders.Add("Accept", "text/plain");

var response = await client.PostAsync(string.Format(GodboltApiScheme, lang), new StringContent(requestJson, Encoding.UTF8, "application/json"));

if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Godbolt returns '{response.StatusCode}' for the request.");
}

return await response.Content.ReadAsStringAsync();
}

protected IHttpClientFactory HttpClientFactory { get; }
}
}
2 changes: 2 additions & 0 deletions src/Modix/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
using Modix.Services.Core;
using Modix.Services.Csharp;
using Modix.Services.EmojiStats;
using Modix.Services.Godbolt;
using Modix.Services.GuildStats;
using Modix.Services.Images;
using Modix.Services.Moderation;
Expand Down Expand Up @@ -174,6 +175,7 @@ public static IServiceCollection AddModix(
services.AddScoped<WikipediaService>();
services.AddScoped<StackExchangeService>();
services.AddScoped<DocumentationService>();
services.AddScoped<GodboltService>();

services.AddScoped<IModerationActionEventHandler, ModerationLoggingBehavior>();
services.AddScoped<INotificationHandler<PromotionActionCreatedNotification>, PromotionLoggingHandler>();
Expand Down