-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Переезд на паттерн "Посетитель" (#4)
* Добавил пакет с контрактом паттерна "Посетитель", на который переведу AST * migration to Visitor.NET 2.0.0 * базис внедрения шаблона Посетитель * move folder * merge * small refactoring + two nodes * fix build * Новая система адресации инструкций (#21) * initial of the branch * контракт адреса * Переезд на .NET 7 (#24) * обновление sdk в проекте * обновление sdk в ci * переход на json raw string literal * обновление nuget пакетов * Генерация отчёта о покрытии на уровне конфигурации проекта coverlet-coverage/coverlet#1391 * Генерация отчёта о покрытии на уровне конфигурации проекта coverlet-coverage/coverlet#1391 * versioning * Update Readme.md * draft алгоритма работы коллекции * Использование последних наворотов шарпа (#26) * versioning * enabling implicit usings (#25) * local scoped namespaces (#27) * after merge * разработка алгоритма вставки в коллекцию * пакетная вставка * доработка алгоритма вставки * индексатор * прямая итерация над коллекцией * важная доработка вставки - сгенерированный адрес проставляется инструкции, больше не требуется создавать адрес для создания инструкции * переименовал сущность адреса * доработка массовой вставки * алгоритм удаления инструкции * unit tests * more tests * переписал новые визиторы на AddressedInstructions * удаление конструкта "номер инструкции" * допиливание работы с Label.cs * удаление конструкта номера из алгоритмов инструкций * прогон инструкций в виртуальной машине по адресу * переписывание алгоритмов инструкций на работу с адресами * текущая реализация не требует такой сложной конструкции инструкции возврата * remove unused * подправил контракт AST * block statement * Proper HasReturnStatementImplementation * removed unused code * перегруппировка * address system refactoring * HashedAddress.cs fix * AddressedInstructions.cs fix * introducing brand new visitor architecture * unary expression visitor * refactoring + error removal * Simple.cs fix * BinaryExpression refactoring * move AddressedInstructions.cs back * remove unused * as string code gen * Constant.cs refactoring * доработка генерации существующих функций ExpressionInstructionProvider.cs * ArrayLiteral.cs visit * TypeStatement.cs fix * InsideLoopStatement.cs visit * ExpressionStatement.cs visit * ReturnStatement.cs visit * Label.cs fix * remove redunant override * Property.cs refactoring * ObjectLiteral.cs + FunctionDeclaration.cs visitor refactoring & decoupling * WhileStatement.cs visit refactoring * IfStatement.cs refactoring with visitor * IfStatement.cs fix * ConditionalExpression.cs visit fix * AssignmentExpression.cs visitor * fix * fix tests * ComplexLiteral.cs * AssignmentExpression visit fix * Исправление некорректной грамматики (#28) * new grammar.txt content * format grammar.txt * grammar fix * MemberExpression.cs visiting * refactoring * fix * replacement function in AddressedInstructions.cs * AssignmentExpression visiting fix * fix * call expr print * fix parser * parser fix 2 * restructuring * script body visit fix * formatting * parser fix * refactoring * semantic assertion draft * break support in if statatement * enum rename * rename * exceptions excluded from codecov * some semantic analysis rework * removed some tests * supress code cov * suppress * ReturnStatement.cs semantic * renane * parser fix * rename * move * mv SemanticChecker.cs * new visitor * region * SymbolTableBuilder.cs completed * module refactoring * removed symbol table construction from parsing * SymbolTableInitializer fix * integration with symbol table initializer * refactoring * DeclarationVisitor.cs * usage of decl visitor * fix recursion * - Visiting type decl - New type symbol - Removed types dict from symbol table * fix * small fix * update nuget * symbol refactoring * some work stuck long time ago * symbol state * предварительная версия инициализатора имён * fix ci * complete type loading system rework * type resolving example * refactoring of default js types consuming and custom types resolving * fix function codegen bug - end label was not emitted * type domain refactored * pre-load built types before reference resolving * fix bug in object type ref resolving * hierarchy enhancement * guard of type duplicates and built-in types declaration * initialized/declared type symbols * some new checks * more refac * proper render of type values * guard declarations from duplicates * do not return null * binary and unary expressions check * fix bug sequence has no elements * guard against no initializer * formatting * there is not symbol without initializer thus symbol cannot be not initialized * working with assignments * checking access expressions * check object literal without methods * реструктуризация сервисов посетителей * рефакторинг после реструктуризации * удалил ненавистный Utils * рефакторинг объектного типа * сохранение функций в хранилище, для которых не был сразу выведен возвращаемый тип, чтобы впоследствии его вычислить * call expr check v1 * fix * перенос проверок функции статическим анализом * Починил бекенд при работе с анонимными массивами и объектами * доработка вывода типов * поправил вывод типов в части необработанных функций * обновление версий экшенов * вторая волна обновлений * upd workflows * global using visitor.net * fix func decl gen * Revert "fix func decl gen" This reverts commit ef97623. * visit fix * Имеет ли функция пустое тело * исправил ошибку кодогенерации if statement при отсутствии else блока * базовая кодогенерация для вызова функции без учета метода объекта * доработка вывода типов * починил статический анализ доступа к элементу массива по индексу * fix * rename to hydrascript * #15 - удалил методы из объекта * #15 - удалил концепцию метода из бекенда * #15 - удалил FunctionType.cs * #15 - статический анализ вызова метода * #15 - кодогенерация вызова метода * #15 - актуализация лексической структуры * #15 - доработка "забытого" статического анализа * #15 - поправил кодген if-else * rm * #15 - если у функции не прописан тип и нет return'ов, то она void * #15 - корректировка примеров * #23 - рабочий пример
- Loading branch information
Showing
278 changed files
with
5,701 additions
and
4,938 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,13 +14,13 @@ jobs: | |
runs-on: ubuntu-latest | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v3 | ||
uses: actions/checkout@v4 | ||
- name: Setup .NET | ||
uses: actions/setup-dotnet@v2 | ||
uses: actions/setup-dotnet@v4 | ||
with: | ||
dotnet-version: 7.0.x | ||
- name: Cache NuGet packages | ||
uses: actions/cache@v3 | ||
uses: actions/cache@v4 | ||
with: | ||
path: ~/.nuget/packages | ||
key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj*') }} | ||
|
@@ -36,9 +36,9 @@ jobs: | |
if: github.event_name == 'pull_request' | ||
uses: 5monkeys/cobertura-action@master | ||
with: | ||
path: ./Interpreter.Tests/coverage.cobertura.xml | ||
path: ./HydraScript.Tests/coverage.cobertura.xml | ||
repo_token: ${{ secrets.GITHUB_TOKEN }} | ||
minimum_coverage: 80 | ||
minimum_coverage: 20 | ||
fail_below_threshold: true | ||
show_class_names: true | ||
show_missing: true | ||
|
@@ -49,21 +49,21 @@ jobs: | |
if: github.ref == 'refs/heads/master' && github.event_name == 'push' | ||
uses: irongut/[email protected] | ||
with: | ||
filename: ./Interpreter.Tests/coverage.cobertura.xml | ||
filename: ./HydraScript.Tests/coverage.cobertura.xml | ||
badge: true | ||
fail_below_min: false | ||
format: markdown | ||
hide_branch_rate: true | ||
hide_complexity: true | ||
thresholds: '80 100' | ||
- name: ReportGenerator | ||
uses: danielpalme/ReportGenerator-GitHub-Action@5.1.10 | ||
uses: danielpalme/ReportGenerator-GitHub-Action@5.2.1 | ||
with: | ||
reports: './Interpreter.Tests/coverage.cobertura.xml' | ||
reports: './HydraScript.Tests/coverage.cobertura.xml' | ||
targetdir: './coverage-report' | ||
- name: Upload coverage report artifact | ||
if: github.event_name == 'push' | ||
uses: actions/upload-artifact@v2.2.3 | ||
uses: actions/upload-artifact@v4 | ||
with: | ||
name: CoverageReport | ||
path: coverage-report |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
using System.Collections; | ||
using HydraScript.Lib.BackEnd.Addresses; | ||
using HydraScript.Lib.BackEnd.Instructions; | ||
|
||
namespace HydraScript.Lib.BackEnd; | ||
|
||
public class AddressedInstructions : IEnumerable<Instruction> | ||
{ | ||
private readonly LinkedList<IAddress> _addresses = new(); | ||
private readonly Dictionary<IAddress, LinkedListNode<IAddress>> _addressToNode = new(); | ||
private readonly Dictionary<LinkedListNode<IAddress>, Instruction> _instructions = new(); | ||
|
||
public Instruction this[IAddress address] | ||
{ | ||
get => _instructions[_addressToNode[address]]; | ||
private set => _instructions[_addressToNode[address]] = value; | ||
} | ||
|
||
public IAddress Start => | ||
_addresses.First?.Value; | ||
|
||
public IAddress End => | ||
_addresses.Last?.Value; | ||
|
||
public void Add(Instruction instruction, string label = null) | ||
{ | ||
IAddress newAddress = label is null | ||
? new HashAddress(seed: instruction.GetHashCode()) | ||
: new Label(label); | ||
instruction.Address = newAddress; | ||
|
||
AddWithAddress(instruction, newAddress); | ||
} | ||
|
||
public void Replace(Instruction old, Instruction @new) | ||
{ | ||
var address = old.Address; | ||
@new.Address = address; | ||
|
||
this[address] = @new; | ||
} | ||
|
||
private void AddWithAddress(Instruction instruction, IAddress newAddress) | ||
{ | ||
var last = _addresses.Last; | ||
if (last is not null) | ||
last.Value.Next = newAddress; | ||
|
||
var newNode = _addresses.AddLast(newAddress); | ||
|
||
_addressToNode.Add(newAddress, newNode); | ||
_instructions.Add(newNode, instruction); | ||
} | ||
|
||
public void AddRange(IEnumerable<Instruction> instructions) | ||
{ | ||
foreach (var instruction in instructions) | ||
AddWithAddress(instruction, instruction.Address); | ||
} | ||
|
||
public void Remove(Instruction instruction) | ||
{ | ||
var address = instruction.Address; | ||
var nodeToRemove = _addressToNode[address]; | ||
|
||
var prev = nodeToRemove.Previous; | ||
if (prev is not null) | ||
{ | ||
prev.Value.Next = nodeToRemove.Next?.Value; | ||
} | ||
|
||
_addressToNode.Remove(address); | ||
_instructions.Remove(nodeToRemove); | ||
_addresses.Remove(nodeToRemove); | ||
} | ||
|
||
public IEnumerator<Instruction> GetEnumerator() => | ||
_addresses.Select(address => this[address]) | ||
.GetEnumerator(); | ||
|
||
IEnumerator IEnumerable.GetEnumerator() => | ||
GetEnumerator(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
namespace HydraScript.Lib.BackEnd.Addresses; | ||
|
||
public class HashAddress : IAddress | ||
{ | ||
private readonly int _seed; | ||
|
||
public IAddress Next { get; set; } | ||
|
||
public HashAddress(int seed) => | ||
_seed = seed; | ||
|
||
public bool Equals(IAddress other) | ||
{ | ||
if (other is HashAddress hashed) | ||
return _seed == hashed._seed; | ||
|
||
return false; | ||
} | ||
|
||
public override int GetHashCode() | ||
{ | ||
var i1 = _seed ^ 17; | ||
var i2 = 31 * _seed + i1; | ||
|
||
return HashCode.Combine(i1, i2); | ||
} | ||
|
||
public override string ToString() => "\t"; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
namespace HydraScript.Lib.BackEnd.Addresses; | ||
|
||
public interface IAddress : IEquatable<IAddress> | ||
{ | ||
IAddress Next { get; set; } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
namespace HydraScript.Lib.BackEnd.Addresses; | ||
|
||
public class Label : IAddress | ||
{ | ||
public string Name { get; } | ||
|
||
public Label(string name) => | ||
Name = name; | ||
|
||
public IAddress Next { get; set; } | ||
|
||
public bool Equals(IAddress other) | ||
{ | ||
if (other is Label label) | ||
return Name == label.Name; | ||
|
||
return false; | ||
} | ||
|
||
public override int GetHashCode() => | ||
Name.GetHashCode(); | ||
|
||
public override string ToString() => | ||
$"{Name}:\n\t"; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
using HydraScript.Lib.BackEnd.Addresses; | ||
|
||
namespace HydraScript.Lib.BackEnd.Instructions; | ||
|
||
public abstract class BlockLabel : Instruction | ||
{ | ||
private readonly BlockPosition _blockPosition; | ||
private readonly BlockType _blockType; | ||
private readonly string _blockId; | ||
|
||
protected BlockLabel(BlockPosition blockPosition, BlockType blockType, string blockId) | ||
{ | ||
_blockPosition = blockPosition; | ||
_blockType = blockType; | ||
_blockId = blockId; | ||
} | ||
|
||
public override IAddress Execute(VirtualMachine vm) => | ||
Address.Next; | ||
|
||
protected override string ToStringInternal() => | ||
$"{_blockPosition}{_blockType} {_blockId}"; | ||
|
||
protected enum BlockPosition | ||
{ | ||
Begin, | ||
End | ||
} | ||
} | ||
|
||
public enum BlockType | ||
{ | ||
Function, | ||
Loop, | ||
Condition | ||
} | ||
|
||
public class BeginBlock : BlockLabel | ||
{ | ||
public BeginBlock(BlockType blockType, string blockId) : | ||
base(BlockPosition.Begin, blockType, blockId) { } | ||
} | ||
|
||
public class EndBlock : BlockLabel | ||
{ | ||
public EndBlock(BlockType blockType, string blockId) : | ||
base(BlockPosition.End, blockType, blockId) { } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
using HydraScript.Lib.BackEnd.Addresses; | ||
|
||
namespace HydraScript.Lib.BackEnd.Instructions; | ||
|
||
public class Halt : Instruction | ||
{ | ||
public override bool End() => true; | ||
|
||
public override IAddress Execute(VirtualMachine vm) | ||
{ | ||
vm.Frames.Pop(); | ||
return new HashAddress(seed: 0); | ||
} | ||
|
||
protected override string ToStringInternal() => "End"; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
using HydraScript.Lib.BackEnd.Addresses; | ||
|
||
namespace HydraScript.Lib.BackEnd.Instructions; | ||
|
||
public abstract class Instruction | ||
{ | ||
private IAddress _address; | ||
|
||
public IAddress Address | ||
{ | ||
get => _address; | ||
set | ||
{ | ||
OnSetOfAddress(value); | ||
_address = value; | ||
} | ||
} | ||
|
||
protected virtual void OnSetOfAddress(IAddress address) { } | ||
|
||
public abstract IAddress Execute(VirtualMachine vm); | ||
|
||
public virtual bool End() => false; | ||
|
||
protected abstract string ToStringInternal(); | ||
|
||
public override string ToString() => | ||
$"{Address}{ToStringInternal()}"; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
using HydraScript.Lib.BackEnd.Addresses; | ||
using HydraScript.Lib.BackEnd.Values; | ||
|
||
namespace HydraScript.Lib.BackEnd.Instructions; | ||
|
||
public class Print : Instruction | ||
{ | ||
private readonly IValue _value; | ||
|
||
public Print(IValue value) => | ||
_value = value; | ||
|
||
public override IAddress Execute(VirtualMachine vm) | ||
{ | ||
vm.Writer.WriteLine(_value.Get(vm.Frames.Peek())); | ||
return Address.Next; | ||
} | ||
|
||
protected override string ToStringInternal() => | ||
$"Print {_value}"; | ||
} |
Oops, something went wrong.