Skip to content

Commit

Permalink
Переезд на паттерн "Посетитель" (#4)
Browse files Browse the repository at this point in the history
* Добавил пакет с контрактом паттерна "Посетитель", на который переведу 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
Stepami authored Jul 20, 2024
1 parent 9c83de8 commit 03d6454
Show file tree
Hide file tree
Showing 278 changed files with 5,701 additions and 4,938 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/cla.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
PERSONAL_ACCESS_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
with:
path-to-signatures: 'signatures.json'
path-to-document: 'https://github.com/Stepami/extended-js-subset/blob/master/contributor-licence-agreement.md'
path-to-document: 'https://github.com/Stepami/hydrascript/blob/master/contributor-licence-agreement.md'
allowlist: Stepami,bot*
branch: 'main'
remote-repository-name: hydrascript-cla-signatures
18 changes: 9 additions & 9 deletions .github/workflows/develop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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*') }}
Expand All @@ -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
Expand All @@ -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
12 changes: 6 additions & 6 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Create release
id: create_release
uses: ncipollo/release-action@v1
Expand All @@ -38,21 +38,21 @@ jobs:
runs-on: ${{ matrix.config.os }}
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: Publish
run: |
mkdir output
dotnet publish ./Interpreter/Interpreter.csproj -c Release -r ${{ matrix.config.rid }} -p:PublishSingleFile=true -p:DebugType=embedded --self-contained false -o ./output
dotnet publish ./HydraScript/HydraScript.csproj -c Release -r ${{ matrix.config.rid }} -p:PublishSingleFile=true -p:DebugType=embedded --self-contained false -o ./output
- name: Upload release assets
uses: shogo82148/actions-upload-release-asset@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_name: interpreter-${{ matrix.config.rid }}${{ matrix.config.rid == 'win-x64' && '.exe' || '' }}
asset_path: ./output/Interpreter${{ matrix.config.rid == 'win-x64' && '.exe' || '' }}
asset_name: hydrascript-${{ matrix.config.rid }}${{ matrix.config.rid == 'win-x64' && '.exe' || '' }}
asset_path: ./output/HydraScript${{ matrix.config.rid == 'win-x64' && '.exe' || '' }}
asset_content_type: ${{ matrix.config.type }}

2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Contributions are welcomed! Here's a few things to know:
## Steps to Contributing

Here are the basic steps to get started with your first contribution. Please reach out with any questions.
1. Use [open issues](https://github.com/stepami/extended-js-subset/issues) to discuss the proposed changes. Create an issue describing changes if necessary to collect feedback. Also, please use provided labels to tag issues so everyone can easily sort issues of interest.
1. Use [open issues](https://github.com/stepami/hydrascript/issues) to discuss the proposed changes. Create an issue describing changes if necessary to collect feedback. Also, please use provided labels to tag issues so everyone can easily sort issues of interest.
1. [Fork the repo](https://help.github.com/articles/fork-a-repo/) in order if you want to make and test local changes.
1. Create a new branch **from master** for the issue. We suggest prefixing the branch with type of contribution (`bugfix`/`feature`), your username and then a descriptive title: (e.g. `bugfix/user1/object-comparision` or `feature/user2/variable-initialization-check`)
1. Make code changes.
Expand Down
6 changes: 3 additions & 3 deletions ExtendedJavaScriptSubset.sln
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interpreter.Lib", "Interpreter.Lib\Interpreter.Lib.csproj", "{83524079-4A56-4AF0-9011-F7CA871536E9}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HydraScript.Lib", "HydraScript.Lib\HydraScript.Lib.csproj", "{83524079-4A56-4AF0-9011-F7CA871536E9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interpreter", "Interpreter\Interpreter.csproj", "{5DA79C0C-2B98-4E64-81EA-92AFFC5204D3}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HydraScript", "HydraScript\HydraScript.csproj", "{5DA79C0C-2B98-4E64-81EA-92AFFC5204D3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interpreter.Tests", "Interpreter.Tests\Interpreter.Tests.csproj", "{F0DD56CB-C68A-4CDC-AA54-0A07342FE08B}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HydraScript.Tests", "HydraScript.Tests\HydraScript.Tests.csproj", "{F0DD56CB-C68A-4CDC-AA54-0A07342FE08B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
83 changes: 83 additions & 0 deletions HydraScript.Lib/BackEnd/AddressedInstructions.cs
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();
}
29 changes: 29 additions & 0 deletions HydraScript.Lib/BackEnd/Addresses/HashAddress.cs
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";
}
6 changes: 6 additions & 0 deletions HydraScript.Lib/BackEnd/Addresses/IAddress.cs
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; }
}
25 changes: 25 additions & 0 deletions HydraScript.Lib/BackEnd/Addresses/Label.cs
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";
}
48 changes: 48 additions & 0 deletions HydraScript.Lib/BackEnd/Instructions/BlockLabel.cs
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) { }
}
16 changes: 16 additions & 0 deletions HydraScript.Lib/BackEnd/Instructions/Halt.cs
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";
}
29 changes: 29 additions & 0 deletions HydraScript.Lib/BackEnd/Instructions/Instruction.cs
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()}";
}
21 changes: 21 additions & 0 deletions HydraScript.Lib/BackEnd/Instructions/Print.cs
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}";
}
Loading

0 comments on commit 03d6454

Please sign in to comment.