Skip to content

Commit

Permalink
Рефакторинг доменной модели (#10)
Browse files Browse the repository at this point in the history
* Переезд на .net 6

* рефакторинг модели типа токена

* обновление пайплайнов в связи с переездом на новый .NET

* Update Readme.md

* update version

* перенос DoubleValueConverter в тело инструкции, поскольку он используется только там

* Черновик контрактов front-end'а интерпретатора

* каркас сущности для внутренностей парсера

* реорганизация папок

* переименование папок по принципу feature directory

* В рамках проектирования модели создан контекст FrontEnd, где находятся сущности, отвечающие за создание AST, включая само AST

* bugfix

* небольшое форматтирование

* bugfix

* небольшие инфраструктурные изменения: поскольку теперь сущности интерпретатора не конструируются на основе исходного текста, с которым придётся работать, то понятие запроса на создание сущности больше не нужно

* suppressing possible NRE using language feature

* Подстроил инфраструктуру под использование новых доменных контрактов

* доработка контрактов доменной модели

* удалил неиспользуемый класс

* Выпилил всё, что связано с оптимизацией

* Применил паттерн Декоратор для реализация логгируемых сущностей

* переместил логгируемые сущности в инфраструктуру, так как, по сути они не относятся к домену

* маштабная реорганизация файлов - 3 верхнеуровневых контекста:

FrontEnd - лексер, парсер (создание AST)
IR - промежуточное представление (AST, проверка семантики)
BackEnd - виртуальная машина и её инструкции

* solution rename

* Спецификация категории тестов

* Небольшой рефакторинг бэкенда

* removed unused usings

* рефакторинг ошибок семантики

* повысил порог coverage до 80%

* рефакторинг печати в виртуальной машине

* реорганизация папок фичи GetTokens

* реорганизация бэкенда

* рефакторинг модели символов и использованием ковариантных вохвращаемых типов

* lexer tests

* fix tests

* more lexer tests

* StructureTests.cs

* реорганизация папок в тестах

* vm tests

* more vm tests

* vm tests refactoring

* factorial unit test

* Instruction.cs refactoring

* coverage

* values tests

* coverage

* coverage

* coverage

* fix Readme.md

* rename file

* Instructions tests

* test suffix

* coverage

* removed unused

* exception guidelines https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/creating-and-throwing-exceptions#defining-exception-classes

* infrastructure coverage
  • Loading branch information
Stepami authored Sep 15, 2022
1 parent 00fd6fb commit 4b1aa2c
Show file tree
Hide file tree
Showing 201 changed files with 1,958 additions and 1,737 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/develop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: 5.0.x
dotnet-version: 6.0.x
- name: Cache NuGet packages
uses: actions/cache@v3
with:
Expand All @@ -29,14 +29,14 @@ jobs:
- name: Build
run: dotnet build --no-restore -c Release -v n
- name: Test
run: dotnet test -c Release --no-build -v n /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura
run: dotnet test -c Release --no-build -v n /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --filter="Category=Unit"
- name: Code Coverage Summary Report For Merge Request
if: github.event_name == 'pull_request'
uses: 5monkeys/cobertura-action@master
with:
path: ./Interpreter.Tests/coverage.cobertura.xml
repo_token: ${{ secrets.GITHUB_TOKEN }}
minimum_coverage: 20
minimum_coverage: 80
fail_below_threshold: true
show_class_names: true
show_missing: true
Expand All @@ -53,5 +53,5 @@ jobs:
format: markdown
hide_branch_rate: true
hide_complexity: true
thresholds: '20 30'
thresholds: '80 100'

2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: 5.0.x
dotnet-version: 6.0.x
- name: Publish
run: |
mkdir output
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System;
using System.Collections.Generic;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using System.Diagnostics.CodeAnalysis;
using Interpreter.Lib.BackEnd.Values;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class AsString : Simple
{
Expand Down Expand Up @@ -35,5 +36,22 @@ public override int Execute(VirtualMachine vm)
}

protected override string ToStringRepresentation() => $"{Left} = {right.right} as string";

[ExcludeFromCodeCoverage]
private class DoubleValueConverter : JsonConverter<double>
{
public override bool CanRead => false;

public override void WriteJson(JsonWriter writer, double value, JsonSerializer serializer) =>
// ReSharper disable once CompareOfFloatsByEqualityOperator
writer.WriteRawValue(value == Math.Truncate(value)
? JsonConvert.ToString(Convert.ToInt64(value))
: JsonConvert.ToString(value));

public override double ReadJson(JsonReader reader, Type objectType,
double existingValue, bool hasExistingValue,
JsonSerializer serializer) =>
throw new NotImplementedException("CanRead is false, so reading is unnecessary");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class BeginFunction : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System;
using System.Collections.Generic;
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class CallFunction : Simple
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Linq;
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class CreateArray : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Collections.Generic;
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class CreateObject : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System.Collections.Generic;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class DotAssignment : Simple
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class Goto : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class Halt : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class IfNotGoto : Goto
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class IndexAssignment : Simple
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,22 @@
using System;
using Interpreter.Lib.VM;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public abstract class Instruction : IComparable<Instruction>, IEquatable<Instruction>
public abstract class Instruction : IComparable<Instruction>
{
public int Number { get; }

public bool Leader { get; set; }

protected Instruction(int number)
{
protected Instruction(int number) =>
Number = number;
}

public virtual int Jump() => Number + 1;

public bool Branch() => Jump() != Number + 1;

public virtual bool End() => false;

public abstract int Execute(VirtualMachine vm);

public int CompareTo(Instruction other) => Number.CompareTo(other.Number);

public bool Equals(Instruction other) => other != null && Number.Equals(other.Number);

public override bool Equals(object obj) => Equals(obj as Instruction);

public override int GetHashCode() => Number;

protected abstract string ToStringRepresentation();

public override string ToString() => $"{Number}: {ToStringRepresentation()}";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class Print : Instruction
{
Expand All @@ -15,7 +13,7 @@ public Print(int number, IValue value) : base(number)

public override int Execute(VirtualMachine vm)
{
Console.WriteLine(_value.Get(vm.Frames.Peek()));
vm.Writer.WriteLine(_value.Get(vm.Frames.Peek()));
return Number + 1;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class PushParameter : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class RemoveFromArray : Instruction
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using System.Collections;
using System.Collections.Generic;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class Return : Instruction, IEnumerable<int>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Interpreter.Lib.VM;
using Interpreter.Lib.VM.Values;
using Interpreter.Lib.BackEnd.Values;

namespace Interpreter.Lib.IR.Instructions
namespace Interpreter.Lib.BackEnd.Instructions
{
public class Simple : Instruction
{
public string Left { get; set; }

protected (IValue left, IValue right) right;
protected string @operator;
protected readonly string @operator;

public Simple(
string left,
Expand Down Expand Up @@ -87,32 +86,6 @@ public override int Execute(VirtualMachine vm)
return Jump();
}

public void ReduceToAssignment()
{
right = ToStringRepresentation().Split('=')[1].Trim() switch
{
var s
when s.EndsWith("+ 0") || s.EndsWith("- 0") ||
s.EndsWith("* 1") || s.EndsWith("/ 1") => (null, right.left),
var s
when s.StartsWith("0 +") || s.StartsWith("1 *") => (null, right.right),
_ => throw new NotImplementedException()
};
@operator = "";
}

public void ReduceToZero()
{
right = ToStringRepresentation().Split('=')[1].Trim() switch
{
"-0" => (null, new Constant(0, "0")),
var s
when s.EndsWith("* 0") || s.StartsWith("0 *") => (null, new Constant(0, "0")),
_ => throw new NotImplementedException()
};
@operator = "";
}

protected override string ToStringRepresentation() =>
right.left == null
? $"{Left} = {@operator}{right.right}"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Interpreter.Lib.VM.Values
namespace Interpreter.Lib.BackEnd.Values
{
public class Constant : IValue
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;

namespace Interpreter.Lib.VM.Values
namespace Interpreter.Lib.BackEnd.Values
{
public interface IValue : IEquatable<IValue>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Interpreter.Lib.VM.Values
namespace Interpreter.Lib.BackEnd.Values
{
public class Name : IValue
{
Expand Down
Loading

0 comments on commit 4b1aa2c

Please sign in to comment.