Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Калентьев Илья tg:@m1nus0ne #241

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions cs/Markdown/Maker/HtmlMaker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Markdown.Tokens.HtmlToken;
using Markdown.Tokens.StringToken;

namespace Markdown.Maker;

public class HtmlMaker : IMaker<RootToken>
{
public RootToken MakeFromTokens(List<StringToken> tokens)
{
throw new NotImplementedException();
}
}
8 changes: 8 additions & 0 deletions cs/Markdown/Maker/IMaker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Markdown.Tokens.StringToken;

namespace Markdown.Maker;

public interface IMaker<T>
{
public T MakeFromTokens(List<StringToken> tokens);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мелочь. Так же как и вместо собственных классов лучше использовать интерфейсы, так и тут лучше использовать IEnumerable, чтобы не завязываться на конкретную реализацию коллекции, если нам нужно просто по ней проитерироваться

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправил

}
10 changes: 10 additions & 0 deletions cs/Markdown/Markdown.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
15 changes: 15 additions & 0 deletions cs/Markdown/Md.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Markdown.Maker;
using Markdown.Parser;
using Markdown.Rendered;

namespace Markdown;

public class Md<TResult>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Честно говоря пока не очень понимаю мотивации использовать тут дженерик. Можешь комментарием к треду или прямо в коде объяснить вкратце мотивацию?

{
public string Render(string input, IParser parser, IMaker<TResult> maker, IRenderer<TResult> renderer)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Довольно много параметров в этом методе передается. Подскажи, почему решил конструктор не использовать?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынес в конструктор

{
var tokens = new MarkdownParser().Parse(input);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тоже не в конструкторе и не в методе параметром передаем. Подскажи, почему именно так решил сделать?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынес в конструктор

var model = maker.MakeFromTokens(tokens);
return renderer.Render(model);
}
}
8 changes: 8 additions & 0 deletions cs/Markdown/Parser/IParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Markdown.Tokens.StringToken;

namespace Markdown.Parser;

public interface IParser
{
public List<StringToken> Parse(string input);
}
12 changes: 12 additions & 0 deletions cs/Markdown/Parser/MarkdownParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Markdown.Parser;
using Markdown.Tokens.StringToken;

namespace Markdown;

public class MarkdownParser : IParser
{
public List<StringToken> Parse(string input)
{
throw new NotImplementedException();
}
}
3 changes: 3 additions & 0 deletions cs/Markdown/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// See https://aka.ms/new-console-template for more information

Console.WriteLine("Hello, World!");
13 changes: 13 additions & 0 deletions cs/Markdown/Renderer/HtmlRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Markdown.Rendered;
using Markdown.Tokens.HtmlToken;
using Markdown.Tokens.StringToken;

namespace Markdown;

public class HtmlRenderer : IRenderer<RootToken>
{
public string Render(RootToken root)
{
throw new NotImplementedException();
}
}
6 changes: 6 additions & 0 deletions cs/Markdown/Renderer/IRednderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Markdown.Rendered;

public interface IRenderer<T>
{
public string Render(T input);
}
12 changes: 12 additions & 0 deletions cs/Markdown/Tokens/HtmlToken/BaseHtmlToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Markdown.Tokens;

public abstract class BaseHtmlToken

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Точно ли этот класс должен содержать "Html" в названии? Мы же парсим Markdown текст, который уже в последствии преобразуем в HTML, но мы можем захотеть и не только в него преобразовать, а и в другой язык разметки. Получится ли быстро это реализовать в текущей архитектуре?
Если я не понял идеи алгоритма, то можешь вкратце ее объяснить, пожалуйста?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Изначально я хотел использовать модель-посредник для трансляции любого формата разметки текста в другой, но решил оставить IEnumerable ее упрощенной версией. Строка -> IEnumerable -> RootToken (репрезентация DOM)

{
public List<BaseHtmlToken>? Children { get; private protected set; }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А точно ли нам нужен здесь nulluble тип? Может нас устроит и просто пустая коллекция, когда дочерних тегов нет?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправил

public string Value { get; private protected set; }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Подскажи, ты осознанно использовал private protected set? Я не против, но если осознанно, то можешь объяснить мотивацию?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всегда использую private, по необходимости расширяю область видимости. Без protected сеттер из дочерних классов становится недоступным


public BaseHtmlToken(List<BaseHtmlToken>? children)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В абстрактном классе у тебя 2 поля, но в конструкторе принимается только одно. Так и задумано?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Например в токене, который будет просто хранить текст Children = {StrongCloseToken(), TextToken(), StrongOpenToken()}

{
Children = children;
}
}
18 changes: 18 additions & 0 deletions cs/Markdown/Tokens/HtmlToken/HtmlTokenWithTag.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace Markdown.Tokens.HtmlToken;

public abstract class HtmlTokenWithTag : BaseHtmlToken
{
public HtmlTokenWithTag(List<BaseHtmlToken>? children) : base(children)
{
//проверка на валидность по типам
}

public abstract Type OpenTypeToken { get; }
public abstract Type CloseTypeToken { get; }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для таких полей обычно используют Enum, подскажи, почему именно Type выбрал?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

После паринга StringToken будет преобразовываться в Open/CloseToken, далее в цельный Token

public abstract string TagValue { get; }

public override string ToString()
{
return $"<{TagValue}>{string.Join("", Children.Select(token => token.ToString()))}</{TagValue}>";
}
}
8 changes: 8 additions & 0 deletions cs/Markdown/Tokens/HtmlToken/RootToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Markdown.Tokens.HtmlToken;

public class RootToken : BaseHtmlToken
{
public RootToken(List<BaseHtmlToken>? children) : base(children)
{
}
}
9 changes: 9 additions & 0 deletions cs/Markdown/Tokens/HtmlToken/Strong/StrongCloseToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Markdown.Tokens.HtmlToken.Strong;

public class StrongCloseToken : BaseHtmlToken
{
public StrongCloseToken(string value) : base(null)
{
Value = value;
}
}
9 changes: 9 additions & 0 deletions cs/Markdown/Tokens/HtmlToken/Strong/StrongOpenToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Markdown.Tokens.HtmlToken.Strong;

public class StrongOpenToken : BaseHtmlToken
{
public StrongOpenToken(string value) : base(null)
{
Value = value;
}
}
12 changes: 12 additions & 0 deletions cs/Markdown/Tokens/HtmlToken/Strong/StrongToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Markdown.Tokens.HtmlToken.Strong;

public class StrongToken : HtmlTokenWithTag
{
public StrongToken(List<BaseHtmlToken>? children) : base(children)
{
}

public override Type OpenTypeToken => typeof(StrongOpenToken);
public override Type CloseTypeToken => typeof(StrongCloseToken);
public override string TagValue => "strong";
}
9 changes: 9 additions & 0 deletions cs/Markdown/Tokens/StringToken/StringToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Markdown.Tokens.StringToken;

public class StringToken(string value, int offset, int length, StringTokenType Type)
{
public int Length = length;
public int Offset = offset;
public string Value = value;
public StringTokenType Type;
}
10 changes: 10 additions & 0 deletions cs/Markdown/Tokens/StringToken/StringTokenType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Markdown.Tokens.StringToken;

public enum StringTokenType
{
Text,
NewLine,
WhiteSpace,
Hash,
Unexpected
}
6 changes: 6 additions & 0 deletions cs/clean-code.sln
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ControlDigit", "ControlDigi
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples", "Samples\Samples.csproj", "{C3EF41D7-50EF-4CE1-B30A-D1D81C93D7FA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Markdown", "Markdown\Markdown.csproj", "{BBF05DDE-F868-48FB-9505-01C3A851AAD8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -27,5 +29,9 @@ Global
{C3EF41D7-50EF-4CE1-B30A-D1D81C93D7FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3EF41D7-50EF-4CE1-B30A-D1D81C93D7FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3EF41D7-50EF-4CE1-B30A-D1D81C93D7FA}.Release|Any CPU.Build.0 = Release|Any CPU
{BBF05DDE-F868-48FB-9505-01C3A851AAD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BBF05DDE-F868-48FB-9505-01C3A851AAD8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BBF05DDE-F868-48FB-9505-01C3A851AAD8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BBF05DDE-F868-48FB-9505-01C3A851AAD8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
3 changes: 3 additions & 0 deletions cs/clean-code.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=4a98fdf6_002D7d98_002D4f5a_002Dafeb_002Dea44ad98c70c/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a0b4bc4d_002Dd13b_002D4a37_002Db37e_002Dc9c6864e4302/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Types and namespaces"&gt;&lt;ElementKinds&gt;&lt;Kind Name="NAMESPACE" /&gt;&lt;Kind Name="CLASS" /&gt;&lt;Kind Name="STRUCT" /&gt;&lt;Kind Name="ENUM" /&gt;&lt;Kind Name="DELEGATE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/Template/=13FAEF5AD10371439A650EAFEB60E612/@KeyIndexDefined">True</s:Boolean>
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/Template/=13FAEF5AD10371439A650EAFEB60E612/Applicability/=Live/@EntryIndexedValue">True</s:Boolean>
<s:String x:Key="/Default/PatternsAndTemplates/LiveTemplates/Template/=13FAEF5AD10371439A650EAFEB60E612/Categories/=Imported_002010_002E10_002E2016/@EntryIndexedValue">Imported 10.10.2016</s:String>
Expand Down