Canon/Canon.Server/Services/CompilerService.cs
Ichirinko dbbab1c761 feat-visualization (#33)
尽管里面有点粪,但还是生成了漂亮的树,就当给树施肥了
剩下一个小问题:未考虑节点的宽度(因为名称不一样长),但目前未发现对图生成的明显影响

Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Reviewed-on: PostGuard/Canon#33
Co-authored-by: Ichirinko <1621543655@qq.com>
Co-committed-by: Ichirinko <1621543655@qq.com>
2024-04-19 14:59:45 +08:00

53 lines
1.7 KiB
C#

using Canon.Core.Abstractions;
using Canon.Core.LexicalParser;
using Canon.Core.SyntaxNodes;
using Canon.Server.Models;
using Canon.Visualization.Services;
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");
CompileResult result = new()
{
SourceCode = sourceCode.Code,
CompileId = Guid.NewGuid().ToString(),
CompiledCode = string.Empty,
SytaxTreeImageFilename = filename
};
await dbContext.CompileResults.AddAsync(result);
await dbContext.SaveChangesAsync();
return new CompileResponse(result);
}
}