Canon/Canon.Server/Services/CompilerService.cs
Ichirinko 366991046a feat: 编译历史记录和代码生成结果(#51)
地址已绑定编译结果,支持历史记录切换功能

Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Reviewed-on: PostGuard/Canon#51
Co-authored-by: Ichirinko <1621543655@qq.com>
Co-committed-by: Ichirinko <1621543655@qq.com>
2024-04-22 21:26:34 +08:00

59 lines
1.9 KiB
C#

using Canon.Core.Abstractions;
using Canon.Core.CodeGenerators;
using Canon.Core.LexicalParser;
using Canon.Core.SyntaxNodes;
using Canon.Server.DataTransferObjects;
using Canon.Server.Entities;
using Canon.Server.Models;
using Microsoft.EntityFrameworkCore;
namespace Canon.Server.Services;
public class CompilerService(
ILexer lexer,
IGrammarParser grammarParser,
CompileDbContext dbContext,
GridFsService gridFsService,
SyntaxTreePresentationService syntaxTreePresentationService,
ILogger<CompilerService> logger)
{
public async Task<CompileResponse> Compile(SourceCode sourceCode)
{
logger.LogInformation("Try to compile: '{}'.", sourceCode.Code);
IQueryable<CompileResult> resultQuery = from item in dbContext.CompileResults
where item.SourceCode == sourceCode.Code
select item;
CompileResult? cachedResult = await resultQuery.FirstOrDefaultAsync();
if (cachedResult is not null)
{
return new CompileResponse(cachedResult);
}
CodeReader reader = new(sourceCode);
IEnumerable<SemanticToken> tokens = lexer.Tokenize(reader);
ProgramStruct root = grammarParser.Analyse(tokens);
await using Stream imageStream = syntaxTreePresentationService.Present(root);
string filename = await gridFsService.UploadStream(imageStream, "image/png");
CCodeBuilder builder = new();
root.GenerateCCode(builder);
CompileResult result = new()
{
SourceCode = sourceCode.Code,
CompileId = Guid.NewGuid().ToString(),
CompiledCode = builder.Build(),
SytaxTreeImageFilename = filename,
CompileTime = DateTime.Now
};
await dbContext.CompileResults.AddAsync(result);
await dbContext.SaveChangesAsync();
return new CompileResponse(result);
}
}