Skip to content

Commit

Permalink
- Adicionadas novas funções para conversão entre texto e números à ún…
Browse files Browse the repository at this point in the history
…idade System. Já existiam funçõs deste tipo, mas somente para strings nativas, agora foi dado o devido suporte para as strings contatas por referência.

- Adicionada a função UltimoErro à unidade System que retorna o código do último erro ocorrido em uma chamada, ou 0 caso não tenha ocorrido erro. O código de erro é atribuido automaticamente pelas funções esternas que podem gerar alguma exceção, por exemplo, a função TextoParaInt. Enquanto ainda não é adicionado suporte nativo a manipulação de exceções à linguagem, essa será a abordagem para lidar com erros.

- Adicionado suporte a zoom para o painel de assembly.

- Adicionada persistência do fator de zoom do console. Desta forma o zoom dado no console será salvo com o fechamento do programa e restaurado quando aberto novamente.

- Adicionados atalhos para os comandos de depuração.

- Adicionados mais exemplos, sugestões dos seguidores dadas no em minha live do Dia do Programador ocorrido em 13/09/2024.

- Painel de depuração de variáveis agora mostra os endereços relativos e absolutos de ambas.

- Painel de stack mostra o deslocamento a partir do ponteiro base para cada linha.

- Corrigida a geração de código envolvendo a concatenação de strings com números.

- Corrigido um bug na geração de código da instrução "quebra".

- Corrigido alguns bugs relacionado a alocação e liberação de variaveis de tipos contados por referência.

- Refatorações menores.
  • Loading branch information
sharivan committed Sep 18, 2024
1 parent 71c8946 commit e3014f2
Show file tree
Hide file tree
Showing 44 changed files with 972 additions and 289 deletions.
4 changes: 4 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[*.cs]

# IDE0008: Usar o tipo explícito
csharp_style_var_elsewhere = true
18 changes: 6 additions & 12 deletions Asm/Assembler.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using System;
using Comp;
using System;
using System.Collections.Generic;
using System.IO;

using Comp;

using VM;

namespace Asm;
Expand Down Expand Up @@ -141,15 +139,15 @@ public void CopyCode(byte[] output)

public void CopyCode(byte[] output, int off, int len)
{
var position = this.output.Position;
long position = this.output.Position;
this.output.Position = 0;
this.output.Read(output, off, len);
this.output.Position = position;
}

public void CopyCode(Stream output)
{
var position = this.output.Position;
long position = this.output.Position;
this.output.Position = 0;
this.output.WriteTo(output);
this.output.Position = position;
Expand All @@ -162,7 +160,7 @@ public void CopyConstantBuffer(byte[] output)

public void CopyConstantBuffer(byte[] output, int off, int len)
{
var position = constantOut.Position;
long position = constantOut.Position;
constantOut.Position = 0;
constantOut.Read(output, off, len);
constantOut.Position = position;
Expand Down Expand Up @@ -433,11 +431,7 @@ public void EmitLoadConst(double number)
public void EmitLoadConst(IntPtr ptr)
{
writer.Write((byte) Opcode.LC64);

if (IntPtr.Size == sizeof(int))
writer.Write((int) ptr);
else
writer.Write((long) ptr);
writer.Write((long) ptr);
}

public void EmitLoadIP()
Expand Down
6 changes: 2 additions & 4 deletions Comp/CompilationUnity.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Collections.Generic;

using Asm;

using Asm;
using Comp.Types;
using System.Collections.Generic;

namespace Comp;

Expand Down
59 changes: 36 additions & 23 deletions Comp/Compiler.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;

using Asm;

using Asm;
using Comp.Lex;
using Comp.Types;
using System;
using System.Collections.Generic;
using System.IO;

namespace Comp;

Expand All @@ -17,7 +15,8 @@ public static int GetAlignedSize(int sizeInBytes, int alignSize = sizeof(int))
return r != 0 ? sizeInBytes + alignSize - r : sizeInBytes;
}

public delegate void CompileError(SourceInterval interval, string message);
public delegate void InternalErrorEvent(Exception e);
public delegate void CompileErrorEvent(SourceInterval interval, string message);

private Lexer lexer;
private readonly List<Label> labels;
Expand All @@ -34,7 +33,8 @@ public static int GetAlignedSize(int sizeInBytes, int alignSize = sizeof(int))

internal int globalVariableOffset;

public event CompileError OnCompileError;
public event InternalErrorEvent OnInternalError;
public event CompileErrorEvent OnCompileError;

public string UnityPath
{
Expand Down Expand Up @@ -246,6 +246,7 @@ private void CompileCast(Context context, Assembler assembler, Assembler beforeC
return;

case PointerType:
{
switch (p.Primitive)
{
case Primitive.VOID:
Expand Down Expand Up @@ -276,6 +277,7 @@ private void CompileCast(Context context, Assembler assembler, Assembler beforeC
}

return;
}

default:
throw new CompilerException(interval, $"Tipo desconhecido: '{toType}'.");
Expand Down Expand Up @@ -495,7 +497,6 @@ private void CompileStatement(Context context, Assembler assembler, Statement st
case BreakStatement b:
{
var breakLabel = context.FindNearestBreakLabel() ?? throw new CompilerException(b.Interval, "Instrução 'quebra' deve estar dentro de um loop.");

assembler.EmitJump(breakLabel);
break;
}
Expand Down Expand Up @@ -728,60 +729,68 @@ private void CompileStatement(Context context, Assembler assembler, Statement st

case ForStatement f:
{
var forAssembler = new Assembler();

Context forContext = new(function, f.Interval, context);

// inicializadores
foreach (var initializer in f.Initializers)
CompileStatement(forContext, assembler, initializer);
CompileStatement(forContext, forAssembler, initializer);

var lblLoop = CreateLabel();
assembler.BindLabel(lblLoop);
forAssembler.BindLabel(lblLoop);

// expressão de controle
var expression = f.Expression;
if (expression != null)
{
var expressionType = CompileExpression(forContext, assembler, expression, out _);
var expressionType = CompileExpression(forContext, forAssembler, expression, out _);
if (!PrimitiveType.IsPrimitiveBool(expressionType))
throw new CompilerException(expression.Interval, "Expressão do tipo bool esperada.");
}
else
{
assembler.EmitLoadConst(true);
forAssembler.EmitLoadConst(true);
}

var lblEnd = CreateLabel();
forContext.PushBreakLabel(lblEnd);

assembler.EmitJumpIfFalse(lblEnd);
forAssembler.EmitJumpIfFalse(lblEnd);

var stm = f.Statement;
CompileStatement(forContext, assembler, stm);
CompileStatement(forContext, forAssembler, stm);

// atualizadores
foreach (var updater in f.Updaters)
{
var updaterType = CompileExpression(forContext, assembler, updater, out var tempVar);
CompilePop(assembler, updaterType);
var updaterType = CompileExpression(forContext, forAssembler, updater, out var tempVar);
CompilePop(forAssembler, updaterType);

tempVar?.Release();
}

assembler.EmitJump(lblLoop);
assembler.BindLabel(lblEnd);
forAssembler.EmitJump(lblLoop);
forAssembler.BindLabel(lblEnd);

forContext.DropBreakLabel();
forContext.Release(assembler);
forContext.Release(forAssembler);

assembler.Emit(forAssembler);
break;
}

case BlockStatement bl:
{
var blockAssembler = new Assembler();

Context blockContext = new(function, bl.Interval, context);
foreach (var stm in bl)
CompileStatement(blockContext, assembler, stm);
CompileStatement(blockContext, blockAssembler, stm);

blockContext.Release(blockAssembler);

blockContext.Release(assembler);
assembler.Emit(blockAssembler);
break;
}

Expand Down Expand Up @@ -848,8 +857,8 @@ internal void CompileFunction(Assembler assembler)
if (function.IsExtern)
return;

var tempAssembler = new Assembler();
Context context = new(function, function.Interval);
Assembler tempAssembler = new();

CompileStatement(context, tempAssembler, function.Block);
context.Release(tempAssembler);
Expand Down Expand Up @@ -1037,6 +1046,10 @@ private bool Compile(string fileName, TextReader input, Assembler assembler)
{
OnCompileError?.Invoke(e.Interval, e.Message);
}
catch (Exception e)
{
OnInternalError?.Invoke(e);
}

return false;
}
Expand Down
5 changes: 2 additions & 3 deletions Comp/CompilerParser.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.IO;

using Comp.Lex;
using Comp.Lex;
using Comp.Types;
using System.IO;

namespace Comp;

Expand Down
22 changes: 12 additions & 10 deletions Comp/Context.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Collections.Generic;

using Asm;

using Asm;
using Comp.Types;
using System.Collections.Generic;

namespace Comp;

Expand Down Expand Up @@ -84,7 +82,7 @@ public bool IsRoot()
return Parent == null;
}

internal Variable DeclareVariable(string name, AbstractType type, SourceInterval interval, bool recursive = true)
internal Variable DeclareVariable(string name, AbstractType type, SourceInterval interval, bool recursive = true, bool tempVar = false)
{
if (variableTable.TryGetValue(name, out var result))
return result;
Expand All @@ -94,9 +92,13 @@ internal Variable DeclareVariable(string name, AbstractType type, SourceInterval

if (Function != null)
{
result = new LocalVariable(Function, name, type, interval, RealOffset);
offset += Compiler.GetAlignedSize(type.Size);
Function.CheckLocalVariableOffset(RealOffset);
int realOffset = RealOffset;
int varOffset = Function.AcquireFreeOffset(type, realOffset, tempVar);
result = new LocalVariable(Function, name, type, interval, varOffset);

int typeSize = Compiler.GetAlignedSize(type.Size);
if (varOffset + typeSize > realOffset)
offset = varOffset - realOffset + typeSize;
}
else
{
Expand All @@ -112,7 +114,7 @@ internal Variable DeclareVariable(string name, AbstractType type, SourceInterval

internal Variable DeclareTemporaryVariable(AbstractType type, SourceInterval interval)
{
var tempVar = DeclareVariable($"@tempvar_{type}_{temporaryVariables.Count}", type, interval, false);
var tempVar = DeclareVariable($"@tempvar_{type}_{temporaryVariables.Count}", type, interval, false, true);
tempVar.Temporary = true;
return tempVar;
}
Expand Down Expand Up @@ -161,7 +163,7 @@ internal void DropBreakLabel()

public Label FindNearestBreakLabel()
{
return breakLabels.Count == 0 ? Parent?.FindNearestBreakLabel() : breakLabels.Pop();
return breakLabels.Count == 0 ? Parent?.FindNearestBreakLabel() : breakLabels.Peek();
}

public void Release(Assembler assembler)
Expand Down
Loading

0 comments on commit e3014f2

Please sign in to comment.