Skip to content

Commit

Permalink
Refactored.
Browse files Browse the repository at this point in the history
  • Loading branch information
kekyo committed May 9, 2024
1 parent 1a67f2e commit 8d77fa4
Show file tree
Hide file tree
Showing 16 changed files with 151 additions and 83 deletions.
23 changes: 20 additions & 3 deletions chibiar/chibiar.core.Tests/ArchiverTestRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using chibicc.toolchain.Logging;
using DiffEngine;

namespace chibiar;
Expand All @@ -32,15 +34,30 @@ static ArchiverTestRunner()
private static readonly string id =
$"{DateTime.Now:yyyyMMdd_HHmmss_fff}_{new Random().Next()}";

public static Task RunAsync(
Func<string, Task> tester,
public static async Task RunAsync(
Func<string, TextWriterLogger, Task> tester,
[CallerMemberName] string memberName = null!)
{
var basePath = Path.GetFullPath(
Path.Combine("tests", id, memberName));

Directory.CreateDirectory(basePath);

return tester(basePath);
var logPath = Path.Combine(basePath, "log.txt");
using var logfs = new FileStream(
logPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
var logtw = new StreamWriter(
logfs, Encoding.UTF8);
var logger = new TextWriterLogger(
LogLevels.Debug, logtw);

try
{
await tester(basePath, logger);
}
finally
{
await logtw.FlushAsync();
}
}
}
12 changes: 7 additions & 5 deletions chibiar/chibiar.core.Tests/ArchiverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
using System.Text;
using System.Threading.Tasks;
using chibicc.toolchain.Archiving;

using chibicc.toolchain.Logging;
using static VerifyNUnit.Verifier;
using static chibiar.ArchiverTestRunner;

Expand All @@ -38,11 +38,13 @@ private static async Task VerifySymbolTableAsync(ZipArchive zip)
[Test]
public Task ArchiveOne()
{
return RunAsync(async basePath =>
return RunAsync(async (basePath, logger) =>
{
logger.Information($"Test runner BasePath={basePath}");

var archivePath = Path.Combine(basePath, "output.a");

var archiver = new Archiver();
var archiver = new Archiver(logger);
var actual = archiver.Add(
archivePath,
SymbolTableModes.Auto,
Expand All @@ -67,11 +69,11 @@ public Task ArchiveOne()
[Test]
public Task ArchiveTwo()
{
return RunAsync(async basePath =>
return RunAsync(async (basePath, logger) =>
{
var archivePath = Path.Combine(basePath, "output.a");

var archiver = new Archiver();
var archiver = new Archiver(logger);
var actual = archiver.Add(
archivePath,
SymbolTableModes.Auto,
Expand Down
36 changes: 32 additions & 4 deletions chibiar/chibiar.core/Archiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using chibiar.cli;
using chibicc.toolchain.Archiving;
using chibicc.toolchain.Internal;
using chibicc.toolchain.IO;
using chibicc.toolchain.Logging;

namespace chibiar;

Expand All @@ -33,7 +36,12 @@ public enum AddResults

public sealed class Archiver
{
private static SymbolList ReadSymbols(
private readonly ILogger logger;

public Archiver(ILogger logger) =>
this.logger = logger;

private SymbolList ReadSymbols(
string objectFilePath,
SymbolTableModes symbolTableMode)
{
Expand All @@ -51,11 +59,11 @@ private static SymbolList ReadSymbols(
}
else
{
return new SymbolList(objectName, new Symbol[0]);
return new SymbolList(objectName, CommonUtilities.Empty<Symbol>());
}
}

public AddResults Add(
internal AddResults Add(
string archiveFilePath,
SymbolTableModes symbolTableMode,
string[] objectFilePaths,
Expand Down Expand Up @@ -105,7 +113,7 @@ public AddResults Add(
Concat(objectFilePaths.Select((objectFilePath, index) =>
new Action(() =>
{
var symbolList = ReadSymbols(objectFilePath, symbolTableMode);
var symbolList = this.ReadSymbols(objectFilePath, symbolTableMode);
symbolLists[index] = symbolList;
}))).
ToArray();
Expand All @@ -124,4 +132,24 @@ public AddResults Add(

return updated ? AddResults.Updated : AddResults.Created;
}

public void Archive(CliOptions options)
{
switch (options.Mode)
{
case ArchiveModes.Add:
if (this.Add(
options.ArchiveFilePath,
options.SymbolTableMode,
options.ObjectFilePaths.ToArray(),
options.IsDryRun) == AddResults.Created &&
!options.IsSilent)
{
this.logger.Information($"creating {Path.GetFileName(options.ArchiveFilePath)}");
}
break;
default:
throw new NotImplementedException();
}
}
}
12 changes: 12 additions & 0 deletions chibiar/chibiar.core/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/////////////////////////////////////////////////////////////////////////////////////
//
// chibicc-toolchain - The specialized backend toolchain for chibicc-cil
// Copyright (c) Kouji Matsui(@kozy_kekyo, @kekyo @mastodon.cloud)
//
// Licensed under MIT: https://opensource.org/licenses/MIT
//
/////////////////////////////////////////////////////////////////////////////////////

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("chibiar.core.Tests")]
35 changes: 20 additions & 15 deletions chibiar/chibiar.core/cli/CliOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using chibicc.toolchain.Logging;

namespace chibiar.cli;

Expand All @@ -28,6 +29,7 @@ public sealed class CliOptions
public bool IsSilent = false;
public SymbolTableModes SymbolTableMode = SymbolTableModes.Auto;
public bool IsDryRun = false;
public LogLevels LogLevel = LogLevels.Warning;
public bool ShowHelp = false;
public readonly List<string> ObjectFilePaths = new();

Expand Down Expand Up @@ -77,8 +79,17 @@ public static CliOptions Parse(string[] args)
options.ShowHelp = true;
continue;
case '-':
switch (arg0.Substring(1).ToLowerInvariant())
switch (arg0.Substring(2).ToLowerInvariant())
{
case "log":
if (args.Length >= index &&
Enum.TryParse<LogLevels>(args[index + 1], true, out var logLevel))
{
index++;
options.LogLevel = logLevel;
continue;
}
break;
case "dryrun":
options.IsDryRun = true;
continue;
Expand Down Expand Up @@ -126,20 +137,14 @@ public static CliOptions Parse(string[] args)

public static void WriteUsage(TextWriter tw)
{
tw.WriteLine($"cil-chibiar [{ThisAssembly.AssemblyVersion},{ThisAssembly.AssemblyMetadata.TargetFrameworkMoniker}] [{ThisAssembly.AssemblyMetadata.CommitId}]");
tw.WriteLine("This is a CIL object archiver, part of chibicc-cil project.");
tw.WriteLine("https://github.com/kekyo/chibicc-cil-toolchain");
tw.WriteLine("Copyright (c) Kouji Matsui");
tw.WriteLine("License under MIT");
tw.WriteLine();
tw.WriteLine("usage: cil-chibiar [options] <archive path> [<obj path> ...]");
tw.WriteLine(" -r Add object files into the archive");
tw.WriteLine(" -c Add object files into the archive silently");
tw.WriteLine(" -s Add symbol table");
tw.WriteLine(" -d Delete object files from the archive");
tw.WriteLine(" -t List object files in the archive");
tw.WriteLine(" --dryrun Need to dryrun");
tw.WriteLine(" -h, --help Show this help");
tw.WriteLine(" -r Add object files into the archive");
tw.WriteLine(" -c Add object files into the archive silently");
tw.WriteLine(" -s Add symbol table");
tw.WriteLine(" -d Delete object files from the archive");
tw.WriteLine(" -t List object files in the archive");
tw.WriteLine(" --log <level> Log level [debug|trace|information|warning|error|silent] (defaulted: warning)");
tw.WriteLine(" --dryrun Need to dryrun");
tw.WriteLine(" -h, --help Show this help");
}
}

Expand Down
31 changes: 16 additions & 15 deletions chibiar/chibiar/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.IO;
using System.Runtime.InteropServices;
using chibiar.cli;
using chibicc.toolchain.Logging;

namespace chibiar;

Expand All @@ -25,27 +26,27 @@ public static int Main(string[] args)
if (options.ShowHelp || options.ObjectFilePaths.Count == 0)
{
Console.WriteLine();
Console.WriteLine($"cil-ecma-chibiar [{ThisAssembly.AssemblyVersion},{ThisAssembly.AssemblyMetadata.TargetFrameworkMoniker}] [{ThisAssembly.AssemblyMetadata.CommitId}]");
Console.WriteLine("This is a CIL object archiver, part of chibicc-cil project.");
Console.WriteLine("https://github.com/kekyo/chibicc-cil-toolchain");
Console.WriteLine("Copyright (c) Kouji Matsui");
Console.WriteLine("License under MIT");
Console.WriteLine();
Console.WriteLine("usage: cil-ecma-chibiar [options] <archive path> [<obj path> ...]");
CliOptions.WriteUsage(Console.Out);
Console.WriteLine();
return 1;
}

var archiver = new Archiver();
using var logger = new TextWriterLogger(
options.LogLevel,
Console.Out);

switch (options.Mode)
{
case ArchiveModes.Add:
if (archiver.Add(
options.ArchiveFilePath,
options.SymbolTableMode,
options.ObjectFilePaths.ToArray(),
options.IsDryRun) == AddResults.Created &&
!options.IsSilent)
{
Console.WriteLine($"cil-chibiar: creating {Path.GetFileName(options.ArchiveFilePath)}");
}
break;
}
logger.Information($"Started. [{ThisAssembly.AssemblyVersion},{ThisAssembly.AssemblyMetadata.TargetFrameworkMoniker}] [{ThisAssembly.AssemblyMetadata.CommitId}]");

var archiver = new Archiver(logger);

archiver.Archive(options);

return 0;
}
Expand Down
7 changes: 7 additions & 0 deletions chibias/chibias/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ public static int Main(string[] args)
if (options.ShowHelp || options.SourceFilePaths.Count == 0)
{
Console.WriteLine();
Console.WriteLine($"cil-ecma-chibias [{ThisAssembly.AssemblyVersion},{ThisAssembly.AssemblyMetadata.TargetFrameworkMoniker}] [{ThisAssembly.AssemblyMetadata.CommitId}]");
Console.WriteLine("This is a stub CIL assembler, part of chibicc-cil project.");
Console.WriteLine("https://github.com/kekyo/chibicc-cil-toolchain");
Console.WriteLine("Copyright (c) Kouji Matsui");
Console.WriteLine("License under MIT");
Console.WriteLine();
Console.WriteLine("usage: cil-ecma-chibias [options] <soruce path> [<soruce path> ...]");
CliOptions.WriteUsage(Console.Out);
Console.WriteLine();
return 1;
Expand Down
7 changes: 0 additions & 7 deletions chibias/chibias/cli/CliOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,6 @@ public static CliOptions Parse(string[] args)

public static void WriteUsage(TextWriter tw)
{
tw.WriteLine($"cil-chibias [{ThisAssembly.AssemblyVersion},{ThisAssembly.AssemblyMetadata.TargetFrameworkMoniker}] [{ThisAssembly.AssemblyMetadata.CommitId}]");
tw.WriteLine("This is a stub CIL assembler, part of chibicc-cil project.");
tw.WriteLine("https://github.com/kekyo/chibicc-cil-toolchain");
tw.WriteLine("Copyright (c) Kouji Matsui");
tw.WriteLine("License under MIT");
tw.WriteLine();
tw.WriteLine("usage: cil-chibias [options] <soruce path> [<soruce path> ...]");
tw.WriteLine(" -o <path> Output object file path");
tw.WriteLine(" --dryrun Need to dryrun");
tw.WriteLine(" -h, --help Show this help");
Expand Down
12 changes: 6 additions & 6 deletions chibild/chibild.core/Generating/ArchivedObjectInputFragment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ private enum RequiredStates
private readonly Dictionary<string, Symbol> variableSymbols;
private readonly Dictionary<string, Symbol> functionSymbols;

private GlobalVariableNode[] globalVariables = Utilities.Empty<GlobalVariableNode>();
private GlobalConstantNode[] globalConstants = Utilities.Empty<GlobalConstantNode>();
private FunctionDeclarationNode[] functions = Utilities.Empty<FunctionDeclarationNode>();
private InitializerDeclarationNode[] initializers = Utilities.Empty<InitializerDeclarationNode>();
private EnumerationNode[] enumerations = Utilities.Empty<EnumerationNode>();
private StructureNode[] structures = Utilities.Empty<StructureNode>();
private GlobalVariableNode[] globalVariables = CommonUtilities.Empty<GlobalVariableNode>();
private GlobalConstantNode[] globalConstants = CommonUtilities.Empty<GlobalConstantNode>();
private FunctionDeclarationNode[] functions = CommonUtilities.Empty<FunctionDeclarationNode>();
private InitializerDeclarationNode[] initializers = CommonUtilities.Empty<InitializerDeclarationNode>();
private EnumerationNode[] enumerations = CommonUtilities.Empty<EnumerationNode>();
private StructureNode[] structures = CommonUtilities.Empty<StructureNode>();

private int requiredState = (int)RequiredStates.Ignore;

Expand Down
3 changes: 2 additions & 1 deletion chibild/chibild.core/Generating/CodeGenerator_Consumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//
/////////////////////////////////////////////////////////////////////////////////////

using chibicc.toolchain.Internal;
using chibicc.toolchain.Logging;
using chibicc.toolchain.Parsing;
using chibild.Internal;
Expand Down Expand Up @@ -796,7 +797,7 @@ private void ConsumeInitializer(
var method = this.SetupMethodDefinition(
IntiializerMethodName,
this.CreatePlaceholderType(),
Utilities.Empty<ParameterDefinition>(),
CommonUtilities.Empty<ParameterDefinition>(),
MethodAttributes.Private | MethodAttributes.Static);
method.ReturnType = context.FallbackModule.TypeSystem.Void;

Expand Down
5 changes: 3 additions & 2 deletions chibild/chibild.core/Generating/CodeGenerator_Emit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//
/////////////////////////////////////////////////////////////////////////////////////

using chibicc.toolchain.Internal;
using chibicc.toolchain.IO;
using chibicc.toolchain.Logging;
using chibicc.toolchain.Parsing;
Expand Down Expand Up @@ -411,7 +412,7 @@ private void EmitMembers(

var fileScopedInitializerNames = (holder.GetFileScopedTypeIfAvailable()?.
Methods.
Select(m => m.Name) ?? Utilities.Empty<string>()).
Select(m => m.Name) ?? CommonUtilities.Empty<string>()).
ToHashSet();
var subIndex = 1;
count = 0;
Expand Down Expand Up @@ -494,7 +495,7 @@ private void EmitMembers(

var initializerNames = (holder.GetDataTypeIfAvailable()?.
Methods.
Select(m => m.Name) ?? Utilities.Empty<string>()).
Select(m => m.Name) ?? CommonUtilities.Empty<string>()).
ToHashSet();
subIndex = 1;
count = 0;
Expand Down
13 changes: 0 additions & 13 deletions chibild/chibild.core/Internal/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,6 @@ internal static class Utilities
[DllImport("libc", SetLastError = true)]
public static extern int chmod(string path, chmodFlags mode);

#if NET40 || NET45
private static class ArrayEmpty<T>
{
public static readonly T[] Empty = new T[0];
}

public static T[] Empty<T>() =>
ArrayEmpty<T>.Empty;
#else
public static T[] Empty<T>() =>
Array.Empty<T>();
#endif

public static string GetDirectoryPath(string path) =>
Path.GetDirectoryName(path) is { } d ?
Path.GetFullPath(string.IsNullOrWhiteSpace(d) ? "." : d) :
Expand Down
Loading

0 comments on commit 8d77fa4

Please sign in to comment.