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

Fixes/branch logic improvements #239

Merged
merged 10 commits into from
Jun 15, 2024
Merged
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
10 changes: 6 additions & 4 deletions compiler/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,19 @@ public static class Defer
public static void Warn(string text) => _print(text, null, null, warnings);
public static void Warn(string text, BaseSyntax posed) => _print(text, posed, null, warnings);
public static void Warn(string text, BaseSyntax posed, DocumentDeclaration doc)
=> _print(text, posed, doc, warnings);
=> _print(text, posed, doc.FileEntity, warnings);

public static void Error(string text) => _print(text, null, null, errors);
public static void Error(string text, BaseSyntax posed) => _print(text, posed, null, errors);
public static void Error(string text, BaseSyntax posed, DocumentDeclaration doc)
=> _print(text, posed, doc.FileEntity, errors);
public static void Error(string text, BaseSyntax posed, FileInfo doc)
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure consistent error handling.

The method _print is used in different ways, which could lead to inconsistencies in how logs are handled. Consider standardizing the input parameters and the way errors are logged.

-        public static void Error(string text, BaseSyntax posed, FileInfo doc)
-            => _print(text, posed, doc, errors);
+        public static void Error(string text, BaseSyntax posed, FileInfo doc)
+        {
+            if (doc == null) throw new ArgumentNullException(nameof(doc));
+            _print(text, posed, doc, errors);
+        }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public static void Error(string text, BaseSyntax posed, FileInfo doc)
public static void Error(string text, BaseSyntax posed, FileInfo doc)
{
if (doc == null) throw new ArgumentNullException(nameof(doc));
_print(text, posed, doc, errors);
}

=> _print(text, posed, doc, errors);

public static void Info(string text) => _print(text, null, null, infos);
public static void Info(string text, BaseSyntax posed) => _print(text, posed, null, infos);
public static void Info(string text, BaseSyntax posed, DocumentDeclaration doc)
=> _print(text, posed, doc, infos);
=> _print(text, posed, doc.FileEntity, infos);

}

Expand All @@ -50,7 +52,7 @@ public static void Info(string text, BaseSyntax posed, DocumentDeclaration doc)
public static void Warn(string s, CompilationTarget t) => t.Logs.Warn.Enqueue($"[orange]WARN[/]: {s}");
public static void Error(string s, CompilationTarget t) => t.Logs.Error.Enqueue($"[red]ERROR[/]: {s}");

private static void _print(string text, BaseSyntax posed, DocumentDeclaration doc, Queue<string> queue)
private static void _print(string text, BaseSyntax posed, FileInfo doc, Queue<string> queue)
{
if (posed is { Transform: null })
{
Expand All @@ -73,7 +75,7 @@ private static void _print(string text, BaseSyntax posed, DocumentDeclaration do
if (doc is not null)
{
strBuilder.Append(
$"\tin '[orange bold]{doc.FileEntity}[/]'.");
$"\tin '[orange bold]{doc}[/]'.");
}

if (posed is not null && doc is not null)
Expand Down
27 changes: 15 additions & 12 deletions compiler/cmd/CompileCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public class CompileSettings : CommandSettings, IProjectSettingProvider
[CommandOption("--print-result-types")]
public bool PrintResultType { get; set; }

[Description("Display exported types table")]
[CommandOption("--disable-optimization|-O")]
public bool DisableOptimization { get; set; }

[Description("Compile into single file")]
[CommandOption("--single-file|-s")]
public bool HasSingleFile { get; set; }
Expand Down Expand Up @@ -48,10 +52,10 @@ public interface IProjectSettingProvider

public abstract class AsyncCommandWithProject<T> : CommandWithProject<T> where T : CommandSettings, IProjectSettingProvider
{
public sealed override int Execute(CommandContext ctx, T settigs, VeinProject project)
=> ExecuteAsync(ctx, settigs, project).Result;
public sealed override int Execute(CommandContext ctx, T settings, VeinProject project)
=> ExecuteAsync(ctx, settings, project).Result;

public abstract Task<int> ExecuteAsync(CommandContext ctx, T settigs, VeinProject project);
public abstract Task<int> ExecuteAsync(CommandContext ctx, T settings, VeinProject project);
}
public abstract class CommandWithProject<T> : Command<T> where T : CommandSettings, IProjectSettingProvider
{
Expand Down Expand Up @@ -111,7 +115,7 @@ public sealed override int Execute(CommandContext ctx, T settings)
return Execute(ctx, settings, project);
}

public abstract int Execute(CommandContext ctx, T settigs, VeinProject project);
public abstract int Execute(CommandContext ctx, T settings, VeinProject project);
}


Expand All @@ -125,9 +129,9 @@ public override int Execute(CommandContext context, CompileSettings settings, Ve
var targets = CompilationTask.Run(project.WorkDir, settings);


foreach (var info in targets.SelectMany(x => x.Logs.Info).Reverse())
foreach (var info in targets.SelectMany(x => x.Logs.Info))
MarkupLine(info.TrimEnd('\n'));
foreach (var info in Log.infos)
foreach (var info in Log.infos.Reverse())
MarkupLine(info.TrimEnd('\n'));

if (new[] { Log.errors.Count, targets.Sum(x => x.Logs.Error.Count) }.Sum() > 0)
Expand All @@ -136,10 +140,10 @@ public override int Execute(CommandContext context, CompileSettings settings, Ve
Write(rule1);
}

foreach (var target in targets.SelectMany(x => x.Logs.Error).Reverse())
foreach (var target in targets.SelectMany(x => x.Logs.Error))
MarkupLine(target);

foreach (var error in Log.errors)
foreach (var error in Log.errors.Reverse())
MarkupLine(error);

if (new[] { Log.warnings.Count, targets.Sum(x => x.Logs.Warn.Count) }.Sum() > 0)
Expand All @@ -148,17 +152,16 @@ public override int Execute(CommandContext context, CompileSettings settings, Ve
Write(rule2);
}

foreach (var warn in targets.SelectMany(x => x.Logs.Warn).Reverse())
foreach (var warn in targets.SelectMany(x => x.Logs.Warn))
MarkupLine(warn);
foreach (var warn in Log.warnings)
foreach (var warn in Log.warnings.Reverse())
MarkupLine(warn);

if (!Log.warnings.Any() && !Log.errors.Any())
MarkupLine($"\n\n\n");
MarkupLine($"\n");

if (new[] { Log.errors.Count, targets.Sum(x => x.Logs.Error.Count) }.Sum() > 0)
{

var rule3 = new Rule($"[red bold]COMPILATION FAILED[/]") {Style = Style.Parse("lime rapidblink")};
Write(rule3);
MarkupLine($"\n");
Expand Down
23 changes: 8 additions & 15 deletions compiler/compilation/CompilationTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,12 @@ namespace vein.compilation;
using vein.fs;
using vein.styles;

public partial class CompilationTask
public partial class CompilationTask(CompilationTarget target, CompileSettings flags)
{
public CompilationTask(CompilationTarget target, CompileSettings flags)
{
_flags = flags;
Project = target.Project;
Target = target;
}

internal VeinProject Project { get; set; }
internal CompilationTarget Target { get; set; }
internal VeinProject Project { get; set; } = target.Project;
internal CompilationTarget Target { get; set; } = target;

internal readonly CompileSettings _flags;
internal readonly CompileSettings _flags = flags;
internal readonly VeinSyntax syntax = new();
internal readonly Dictionary<FileInfo, string> Sources = new ();
internal ProgressTask Status;
Expand All @@ -43,7 +36,7 @@ public CompilationTask(CompilationTarget target, CompileSettings flags)
internal GeneratorContext Context;
internal List<VeinArtifact> artifacts { get; } = new();

private Dictionary<IdentifierExpression, VeinClass> KnowClasses = new ();
private readonly Dictionary<IdentifierExpression, VeinClass> KnowClasses = new ();

private static string PleaseReportProblemInto()
=> $"Please report the problem into 'https://github.com/vein-lang/vein/issues'.";
Expand Down Expand Up @@ -205,17 +198,17 @@ private bool ProcessFiles(IReadOnlyCollection<FileInfo> files, IReadOnlyCollecti
}
catch (VeinParseException e)
{
Log.Defer.Error($"[red bold]{e.Message.Trim().EscapeMarkup()}[/]\n\tin '[orange bold]{key}[/]'.");
Log.Defer.Error($"[red bold]{e.Message.Trim().EscapeMarkup()}[/]", e.AstItem, key);
read_task.FailTask();
return false;
}
}

read_task.SuccessTask();

Context = new GeneratorContext();
Context = new(new(_flags.DisableOptimization));

module = new VeinModuleBuilder(Project.Name, Project.Version.Version, Types.Storage);
module = new(Project.Name, Project.Version.Version, Types.Storage);

Context.Module = module;
Context.Module.Deps.AddRange(deps);
Expand Down
2 changes: 1 addition & 1 deletion compiler/compilation/parts/bodies.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private void GenerateBody(MethodBuilder method, BlockSyntax block, DocumentDecla
var generator = method.GetGenerator();
Context.Document = doc;
Context.CurrentMethod = method;
Context.CreateScope();
using var scope = Context.CreateScope();
generator.StoreIntoMetadata("context", Context);

foreach (var statement in block.Statements)
Expand Down
4 changes: 3 additions & 1 deletion compiler/veinc.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
<PropertyGroup>
<AssemblyName>veinc</AssemblyName>
<RootNamespace>vein</RootNamespace>
<OutputType>Exe</OutputType>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DeviceId" Version="6.6.0" />
Expand Down
18 changes: 7 additions & 11 deletions lib/ast/stl/VeinParserExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static T ParseVein<T>(this Parser<T> parser, string input)
return result.Value;
}
throw new VeinParseException(result.Message,
new Position(result.Remainder.Position, result.Remainder.Line, result.Remainder.Column));
new Position(result.Remainder.Position, result.Remainder.Line, result.Remainder.Column), null);
}

/// <summary>
Expand Down Expand Up @@ -116,11 +116,9 @@ public static Parser<D> Then<T, D>(this Parser<T> parser, Parser<D> then) =>
public static ExchangeWrapper<T> Exchange<T>(this Parser<T> p)
=> new(p);

public struct ExchangeWrapper<T>
public struct ExchangeWrapper<T>(Parser<T> _1)
{
public ExchangeWrapper(Parser<T> _1) => this._ = _1;
public Parser<T> _;

public Parser<T> _ = _1;
public Parser<D> Return<D>() where D : class, new() => _.Return(new D());
}
}
Expand All @@ -131,12 +129,10 @@ public interface ICommentParserProvider
IComment CommentParser { get; }
}

public class VeinParseException : ParseException
public class VeinParseException(string message, Position pos, BaseSyntax astItem)
: ParseException($"{message}", pos)
{
public VeinParseException(string message, Position pos)
: base($"{message} at {pos}", pos) =>
this.ErrorMessage = message;

public string ErrorMessage { get; set; }
public string ErrorMessage { get; set; } = message;
public BaseSyntax AstItem { get; } = astItem;
}
}
37 changes: 28 additions & 9 deletions lib/ast/syntax/ErrorDiff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
{
try
{
var (diff, arrow_line) = DiffError(t, doc);
var (diff, arrow_line) = DiffError(t, doc.SourceLines);
if (diff is null && arrow_line is null)
return "";
return $"\n\t[grey] {diff.EscapeMarkup().EscapeArgumentSymbols()} [/]\n\t[red] {arrow_line.EscapeMarkup().EscapeArgumentSymbols()} [/]";
Expand All @@ -22,15 +22,32 @@
}
}

private static (string line, string arrow_line) NewDiffError(Transform t, DocumentDeclaration doc)
public static string DiffErrorFull(this Transform t, FileInfo doc)

Check failure on line 25 in lib/ast/syntax/ErrorDiff.cs

View workflow job for this annotation

GitHub Actions / build_all (ubuntu-latest, linux-x64, true)

The type or namespace name 'FileInfo' could not be found (are you missing a using directive or an assembly reference?)
Copy link
Contributor

Choose a reason for hiding this comment

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

Add missing import for FileInfo.

The FileInfo class is used but not imported, causing a build failure. Add the necessary using System.IO; directive at the top of the file.

+ using System.IO;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public static string DiffErrorFull(this Transform t, FileInfo doc)
+ using System.IO;
public static string DiffErrorFull(this Transform t, FileInfo doc)
Tools
GitHub Check: build_all (ubuntu-latest, linux-x64, true)

[failure] 25-25:
The type or namespace name 'FileInfo' could not be found (are you missing a using directive or an assembly reference?)

{
if (doc is null)
try
{
var (diff, arrow_line) = DiffError(t, doc.ReadAllLines());
if (diff is null && arrow_line is null)
return "";
return $"\n\t[grey] {diff.EscapeMarkup().EscapeArgumentSymbols()} [/]\n\t[red] {arrow_line.EscapeMarkup().EscapeArgumentSymbols()} [/]";
}
catch
{
return ""; // TODO analytic
}
}

private static (string line, string arrow_line) NewDiffError(Transform t, string[] sourceLines)
{
if (sourceLines is null)
return default;
if (sourceLines.Length == 0)
return default;
var line = doc.SourceLines[t.pos.Line].Length < t.len ?
var line = sourceLines[t.pos.Line - 1].Length < t.len ?
t.pos.Line :
t.pos.Line - 1;

var original = doc.SourceLines[line];
var original = sourceLines[line - 1];

int takeLen()
{
Expand All @@ -48,25 +65,27 @@
$"{new string(' ', space1.Length)}{new string('^', err_line.Length)}{new string(' ', space2.Length)}");
}

public static (string line, string arrow_line) DiffError(this Transform t, DocumentDeclaration doc)
public static (string line, string arrow_line) DiffError(this Transform t, string[] sourceLines)
{
try
{
return NewDiffError(t, doc);
return NewDiffError(t, sourceLines);
}
catch { }

var line = doc.SourceLines[t.pos.Line].Length < t.len ?
var line = sourceLines[t.pos.Line].Length < t.len ?
t.pos.Line - 1 :
/*t.pos.Line*/throw new Exception("cannot detect line");

var original = doc.SourceLines[line];
var original = sourceLines[line];
var err_line = original[(t.pos.Column - 1)..];
var space1 = original[..(t.pos.Column - 1)];
var space2 = (t.pos.Column - 1) + t.len > original.Length ? "" : original[((t.pos.Column - 1) + t.len)..];

return (original,
$"{new string(' ', space1.Length)}{new string('^', err_line.Length)}{new string(' ', space2.Length)}");
}


}
}
46 changes: 23 additions & 23 deletions lib/ast/syntax/PreviewParseExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,36 +53,36 @@ public static Parser<T> OrPreview<T>(this Parser<T> first, Parser<T> other)

public static Parser<T> PreviewMultiple<T>(this Parser<T> first, params Parser<T>[] others)
where T : BaseSyntax, IPositionAware<T>, IPassiveParseTransition, new() => i =>
{
var results = new[] {first}.Concat(others).Select(x => x(i)).ToArray();
{
var results = new[] {first}.Concat(others).Select(x => x(i)).ToArray();

var succeeded = results.FirstOrDefault(x => x.WasSuccessful);
var succeeded = results.FirstOrDefault(x => x.WasSuccessful);

if (succeeded is not null)
return Success(succeeded.Value, succeeded.Remainder);
if (succeeded is not null)
return Success(succeeded.Value, succeeded.Remainder);

if (results.All(x => !x.WasSuccessful))
{
if (i.Memos.IsEnabled(MemoFlags.NextFail))
{
i.Memos.Disable(MemoFlags.NextFail);
return DetermineBestErrors(results);
}
}
if (results.All(x => !x.WasSuccessful))
{
if (i.Memos.IsEnabled(MemoFlags.NextFail))
{
i.Memos.Disable(MemoFlags.NextFail);
return DetermineBestErrors(results);
}
}

if (!i.IsEffort(results))
return DetermineBestErrors(results);
if (!i.IsEffort(results))
return DetermineBestErrors(results);

var r = AnyChar.Until(Char(';'))(i);
var r = AnyChar.Until(Char(';'))(i);

var error = new T();
error.SetPos(FromInput(i), r.Remainder.Position - i.Position);
var error = new T();
error.SetPos(FromInput(i), r.Remainder.Position - i.Position);

var bestResult = DetermineBestErrors(results);
error.Error = new PassiveParseError(bestResult.Message, bestResult.Expectations);
r.Remainder.Memos.Enable(MemoFlags.NextFail);
return Success(error, r.Remainder);
};
var bestResult = DetermineBestErrors(results);
error.Error = new PassiveParseError(bestResult.Message, bestResult.Expectations);
r.Remainder.Memos.Enable(MemoFlags.NextFail);
return Success(error, r.Remainder);
};


private static bool IsEffort<T>(this IInput current, params IResult<T>[] attempts)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,5 @@ namespace vein.syntax;
using Sprache;
using stl;

public class CorruptedChainException : VeinParseException
{
public CorruptedChainException(ExpressionSyntax e) :
base($"Transform is not found in '{e.ExpressionString}'", new Position(0, 0, 0))
{
}
}
public class CorruptedChainException(ExpressionSyntax e)
: VeinParseException($"Transform is not found in '{e.ExpressionString}'", new Position(0, 0, 0), e);
Loading
Loading