Add sources

This commit is contained in:
Benjamin Moir
2025-03-15 19:52:41 +10:00
parent cd554e19b8
commit d64a36eca1
29 changed files with 3451 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
* text eol=lf
+401
View File
@@ -0,0 +1,401 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
+5
View File
@@ -0,0 +1,5 @@
<Project>
<PropertyGroup>
<UseArtifactsOutput>true</UseArtifactsOutput>
</PropertyGroup>
</Project>
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>xdl</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+14
View File
@@ -0,0 +1,14 @@
namespace XDLCompiler;
public sealed class AbiAddedAttribute(AttributeNode node) : IAttributeFactory<AbiAddedAttribute>
{
public Version Version { get; } = new(
(int)(long)node.Arguments[0].Evaluate(),
(int)(long)node.Arguments[1].Evaluate(),
(int)(long)node.Arguments[2].Evaluate(),
(int)(long)node.Arguments[3].Evaluate());
static string IAttributeFactory<AbiAddedAttribute>.Name => "added";
static AbiAddedAttribute IAttributeFactory<AbiAddedAttribute>.Create(AttributeNode node) => new(node);
}
+14
View File
@@ -0,0 +1,14 @@
namespace XDLCompiler;
public sealed class AbiRemovedAttribute(AttributeNode node) : IAttributeFactory<AbiRemovedAttribute>
{
public Version Version { get; } = new(
(int)(long)node.Arguments[0].Evaluate(),
(int)(long)node.Arguments[1].Evaluate(),
(int)(long)node.Arguments[2].Evaluate(),
(int)(long)node.Arguments[3].Evaluate());
static string IAttributeFactory<AbiRemovedAttribute>.Name => "removed";
static AbiRemovedAttribute IAttributeFactory<AbiRemovedAttribute>.Create(AttributeNode node) => new(node);
}
+235
View File
@@ -0,0 +1,235 @@
using System.CodeDom.Compiler;
namespace XDLCompiler;
public static class CFormatter
{
public static void Write(MemberNode node, TextWriter writer, Dictionary<string, string> remap)
{
if (node is FieldNode field)
Write(field, writer, remap);
else if (node is MethodNode method)
Write(method, writer, remap);
}
public static void Write(FieldNode node, TextWriter writer, Dictionary<string, string> remap)
{
if (Write(node.Type, writer, remap, node.Name) && !string.IsNullOrEmpty(node.Name))
{
if (node.Type is not ArrayTypeNode)
{
writer.Write(' ');
}
}
if (node.Type is not ArrayTypeNode)
writer.Write(node.Name);
if (node.BitWidth != null)
{
writer.Write(" : ");
writer.Write(node.BitWidth.Evaluate());
}
}
public static void Write(ParameterNode node, TextWriter writer, Dictionary<string, string> remap)
{
if (Write(node.Type, writer, remap, node.Name) && !string.IsNullOrEmpty(node.Name))
{
if (node.Type is not ArrayTypeNode)
{
writer.Write(' ');
}
}
if (node.Type is not ArrayTypeNode)
{
writer.Write(node.Name);
}
}
public static void Write(MethodNode node, TextWriter writer, Dictionary<string, string> remap)
{
if (node.IsStatic)
writer.Write("static ");
if (node.ForceInline)
writer.Write("FORCEINLINE ");
if (node.TryGetAttribute<RegReturnAttribute>(out _))
{
writer.Write("reg_return_t<");
Write(node.Signature.ReturnType, writer, remap, identifier: null);
writer.Write("> ");
}
else if (Write(node.Signature.ReturnType, writer, remap, identifier: null))
{
writer.Write(' ');
}
writer.Write(node.Name);
writer.Write('(');
for (int i = 0; i < node.Signature.Parameters.Length; i++)
{
if (i > 0)
writer.Write(", ");
Write(node.Signature.Parameters[i], writer, remap);
}
writer.Write(')');
}
// Returns whether a space is needed to separate from an identifier
public static bool Write(TypeNode node, TextWriter writer, Dictionary<string, string> remap, string? identifier)
{
if (node is PointerOrReferenceTypeNode pointer)
return Write(pointer, writer, remap, identifier);
if (node is NamedTypeNode named)
return Write(named, writer, remap);
if (node is TypeDeclarationNode union)
return Write(union, writer, remap);
if (node is ArrayTypeNode array)
return Write(array, writer, remap, identifier);
return false;
}
public static bool Write(TypeDeclarationNode node, TextWriter writer, Dictionary<string, string> remap)
{
return WriteCore(node, new IndentedTextWriter(writer), remap);
static bool WriteCore(TypeDeclarationNode node, IndentedTextWriter writer, Dictionary<string, string> remap)
{
writer.Write(node.DeclarationType);
if (!string.IsNullOrEmpty(node.Name))
{
writer.Write(' ');
if (remap.TryGetValue(node.Name, out var name))
writer.Write(name);
else
writer.Write(node.Name);
}
if (node.Members.IsDefault)
return true;
writer.WriteLine();
writer.WriteLine('{');
writer.Indent++;
foreach (var member in node.Members)
{
Write(member, writer, remap);
writer.WriteLine(';');
}
writer.Indent--;
writer.Write('}');
if (node.IsConst)
{
writer.Write(' ');
writer.Write("const");
}
return true;
}
}
public static bool Write(NamedTypeNode node, TextWriter writer, Dictionary<string, string> remap)
{
if (remap.TryGetValue(node.Name, out var name))
writer.Write(name);
else
writer.Write(node.Name);
if (node.IsConst)
writer.Write(" const");
return true;
}
public static bool Write(PointerOrReferenceTypeNode node, TextWriter writer, Dictionary<string, string> remap, string? identifier)
{
if (node.ElementType is MethodTypeNode method)
{
Write(method.ReturnType, writer, remap, identifier);
writer.Write('(');
writer.Write(node is PointerTypeNode ? '*' : '&');
if (!string.IsNullOrEmpty(identifier))
writer.Write(identifier);
writer.Write(')');
writer.Write('(');
for (int i = 0; i < method.Parameters.Length; i++)
{
if (i > 0)
writer.Write(", ");
Write(method.Parameters[i], writer, remap);
}
writer.Write(')');
if (node.IsConst)
writer.Write(" const");
return true;
}
Write(node.ElementType, writer, remap, identifier);
if (node.ElementType.IsConst || node.ElementType is not PointerOrReferenceTypeNode)
writer.Write(' ');
writer.Write(node is PointerTypeNode ? '*' : '&');
if (node.IsConst)
{
writer.Write("const");
return true;
}
return false;
}
public static bool Write(ArrayTypeNode node, TextWriter writer, Dictionary<string, string> remap, string? identifier)
{
var elementType = node.ElementType;
while (elementType is ArrayTypeNode array)
elementType = array.ElementType;
bool needSpace = Write(elementType, writer, remap, null);
if (!string.IsNullOrEmpty(identifier))
{
if (needSpace)
writer.Write(' ');
writer.Write(identifier);
}
for (var array = node; array != null; array = array.ElementType as ArrayTypeNode)
{
writer.Write('[');
if (array.Length != null)
writer.Write(array.Length.Evaluate());
writer.Write(']');
}
return false;
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace XDLCompiler;
public sealed class ConditionalAttribute(AttributeNode node) : IAttributeFactory<ConditionalAttribute>
{
public string Condition { get; } = node.Arguments[0].Evaluate().ToString()!;
static string IAttributeFactory<ConditionalAttribute>.Name => "conditional";
static ConditionalAttribute IAttributeFactory<ConditionalAttribute>.Create(AttributeNode node) => new(node);
}
+8
View File
@@ -0,0 +1,8 @@
namespace XDLCompiler;
public sealed class ForceAbiAttribute : IAttributeFactory<ForceAbiAttribute>
{
static string IAttributeFactory<ForceAbiAttribute>.Name => "force_abi";
static ForceAbiAttribute IAttributeFactory<ForceAbiAttribute>.Create(AttributeNode node) => new();
}
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
using XDLCompiler;
public interface IAttributeFactory<TAttribute>
where TAttribute : IAttributeFactory<TAttribute>
{
static abstract string Name { get; }
static abstract TAttribute Create(AttributeNode node);
}
+27
View File
@@ -0,0 +1,27 @@
namespace XDLCompiler;
public interface ISyntaxVisitor
{
void Visit(AttributeNode node);
void Visit(InterfaceNode node);
void Visit(EnumNode node);
void Visit(UnionNode node);
void Visit(StructNode node);
void Visit(ClassNode node);
void Visit(BaseTypeNode node);
void Visit(MemberBlockNode node);
void Visit(FieldNode node);
void Visit(EnumMemberNode node);
void Visit(MethodNode node);
void Visit(ParameterNode node);
void Visit(PointerTypeNode node);
void Visit(ReferenceTypeNode node);
void Visit(NamedTypeNode node);
void Visit(MethodTypeNode node);
void Visit(IdentifierExpressionNode node);
void Visit(IntegerLiteralNode node);
void Visit(StringLiteralNode node);
void Visit(UnaryNegationNode node);
void Visit(ArrayTypeNode node);
void Visit(ImportNode node);
}
+144
View File
@@ -0,0 +1,144 @@
namespace XDLCompiler;
public static class MemoryExtensions
{
/// <summary>Truncates the span at the first occurrence of the specified value.</summary>
public static ReadOnlySpan<T> TruncateAt<T>(this ReadOnlySpan<T> span, T value)
where T : IEquatable<T>
{
int index = span.IndexOf(value);
return index == -1 ? span : span[..index];
}
/// <summary>Truncates the span at the first occurrence of the specified value.</summary>
public static Span<T> TruncateAt<T>(this Span<T> span, T value)
where T : IEquatable<T>
{
int index = span.IndexOf(value);
return index == -1 ? span : span[..index];
}
/// <summary>Truncates the span at the first occurrence of the specified value.</summary>
public static ReadOnlySpan<T> TruncateAt<T>(this ReadOnlySpan<T> span, T value, int startIndex)
where T : IEquatable<T>
{
int index = span.IndexOf(value, startIndex);
return index == -1 ? span : span[..index];
}
/// <summary>Truncates the span at the first occurrence of the specified value.</summary>
public static Span<T> TruncateAt<T>(this Span<T> span, T value, int startIndex)
where T : IEquatable<T>
{
int index = ((ReadOnlySpan<T>)span).IndexOf(value, startIndex);
return index == -1 ? span : span[..index];
}
/// <summary>Searches for the specified value and returns the index of its first occurrence.</summary>
public static int IndexOf<T>(this ReadOnlySpan<T> span, T value, int startIndex)
where T : IEquatable<T>
{
int index = span[startIndex..].IndexOf(value);
return index == -1 ? -1 : startIndex + index;
}
/// <summary>Searches for the specified value and returns the index following its first occurrence.</summary>
public static int IndexAfter<T>(this ReadOnlySpan<T> span, T value, int startIndex)
where T : IEquatable<T>
{
int index = span[startIndex..].IndexOf(value);
return index == -1 ? -1 : startIndex + index + 1;
}
/// <summary>Searches for the specified value and returns the index of its first occurrence.</summary>
public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value, int startIndex)
where T : IEquatable<T>
{
int index = span[startIndex..].IndexOf(value);
return index == -1 ? -1 : startIndex + index;
}
/// <summary>Searches for the specified value and returns the index following its first occurrence.</summary>
public static int IndexAfter<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value, int startIndex)
where T : IEquatable<T>
{
int index = span[startIndex..].IndexOf(value);
return index == -1 ? -1 : startIndex + index + value.Length;
}
/// <summary>Searches for the specified value and returns the index of its last occurrence.</summary>
public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value, int startIndex)
where T : IEquatable<T>
{
int index = span[startIndex..].LastIndexOf(value);
return index == -1 ? -1 : startIndex + index;
}
/// <summary>Searches for the specified value and returns the index of its last occurrence.</summary>
public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value, int startIndex)
where T : IEquatable<T>
{
int index = span[startIndex..].LastIndexOf(value);
return index == -1 ? -1 : startIndex + index;
}
/// <summary>Searches for the specified value and returns the index of its first occurrence that is not preceded by <paramref name="escape"/>.</summary>
public static int IndexOf<T>(this ReadOnlySpan<T> span, T value, T escape)
where T : IEquatable<T>
{
return IndexOf(span, value, escape, startIndex: 0);
}
/// <summary>Searches for the specified value and returns the index of its first occurrence that is not preceded by <paramref name="escape"/>.</summary>
public static int IndexOf<T>(this ReadOnlySpan<T> span, T value, T escape, int startIndex)
where T : IEquatable<T>
{
int index = span.IndexOf(value, startIndex);
if (index <= 0)
return index;
while (span[index - 1].Equals(escape))
{
int i;
// Count the number of escape characters.
for (i = index - 2; i >= 0; i--)
{
if (!span[i].Equals(escape))
{
break;
}
}
// If we have an even number of escape characters
// preceding the value, the value is not escaped.
if (((index - 1 - i) & 1) == 0)
return index;
else
index = span.IndexOf(value, index + 1);
if (index == -1)
{
return -1;
}
}
return index;
}
/// <summary>Searches for the specified value and returns the index following its first occurrence that is not preceded by <paramref name="escape"/>.</summary>
public static int IndexAfter<T>(this ReadOnlySpan<T> span, T value, T escape)
where T : IEquatable<T>
{
return IndexAfter(span, value, escape, startIndex: 0);
}
/// <summary>Searches for the specified value and returns the index following its first occurrence that is not preceded by <paramref name="escape"/>.</summary>
public static int IndexAfter<T>(this ReadOnlySpan<T> span, T value, T escape, int startIndex)
where T : IEquatable<T>
{
int index = IndexOf(span, value, escape, startIndex);
return index == -1 ? -1 : index + 1;
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace XDLCompiler;
public sealed class NoEmitAttribute : IAttributeFactory<NoEmitAttribute>
{
static string IAttributeFactory<NoEmitAttribute>.Name => "no_emit";
static NoEmitAttribute IAttributeFactory<NoEmitAttribute>.Create(AttributeNode node) => new();
}
+8
View File
@@ -0,0 +1,8 @@
namespace XDLCompiler;
public sealed class NoUuidAttribute : IAttributeFactory<NoUuidAttribute>
{
static string IAttributeFactory<NoUuidAttribute>.Name => "no_uuid";
static NoUuidAttribute IAttributeFactory<NoUuidAttribute>.Create(AttributeNode node) => new();
}
+28
View File
@@ -0,0 +1,28 @@
using XDLCompiler;
using System.CodeDom.Compiler;
Run(args);
static void Run(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("usage: xdl input.xdl output_dir [factory_name]");
return;
}
var generator = new HeaderGenerator();
var headerName = generator.GetHeaderName(args[0]);
using (var file = new StreamWriter(File.Create(Path.Combine(args[1], headerName))))
using (var writer = new IndentedTextWriter(file))
{
generator.GenerateHeader(args[0], args.Length > 2 ? args[2] : null, writer);
}
using (var file = new StreamWriter(File.Create(Path.Combine(args[1], "impls_" + headerName))))
using (var writer = new IndentedTextWriter(file))
{
generator.GenerateImpls(writer);
}
}
+19
View File
@@ -0,0 +1,19 @@
using System.Runtime.InteropServices;
namespace XDLCompiler;
[StructLayout(LayoutKind.Sequential)]
public struct RawGuid
{
public int A;
public short B;
public short C;
public byte D;
public byte E;
public byte F;
public byte G;
public byte H;
public byte I;
public byte J;
public byte K;
}
+8
View File
@@ -0,0 +1,8 @@
namespace XDLCompiler;
public sealed class RegReturnAttribute : IAttributeFactory<RegReturnAttribute>
{
static string IAttributeFactory<RegReturnAttribute>.Name => "reg_return";
static RegReturnAttribute IAttributeFactory<RegReturnAttribute>.Create(AttributeNode node) => new();
}
+275
View File
@@ -0,0 +1,275 @@
using System.Collections.Immutable;
namespace XDLCompiler;
/// <summary></summary>
public interface INamedNode
{
string? Name { get; }
}
/// <summary></summary>
public interface IAttributableNode
{
ImmutableArray<AttributeNode> Attributes { get; }
}
/// <summary>Base class for all syntax nodes.</summary>
public abstract record SyntaxNode
{
/// <summary>Accepts a visitor for traversing the syntax tree</summary>
public abstract void Accept(ISyntaxVisitor visitor);
}
public sealed record ImportNode(StringLiteralNode FileName) : SyntaxNode
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>A syntax node representing an attribute.</summary>
public sealed record AttributeNode(ImmutableArray<ExpressionNode> Arguments, string Name) : SyntaxNode, INamedNode
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public abstract record TypeDeclarationNode(
ImmutableArray<AttributeNode> Attributes,
string? Name,
ImmutableArray<BaseTypeNode> BaseTypes,
ImmutableArray<MemberNode> Members,
bool IsConst = false) : TypeNode(IsConst), IAttributableNode, INamedNode
{
public abstract string DeclarationType { get; }
}
public sealed record EnumMemberNode(
ImmutableArray<AttributeNode> Attributes,
string Name,
ExpressionNode? Value) : MemberNode(Attributes, Name)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record EnumNode(
ImmutableArray<AttributeNode> Attributes,
string? Name,
BaseTypeNode? BaseType,
ImmutableArray<EnumMemberNode> EnumMembers,
bool IsConst = false) : TypeDeclarationNode(Attributes, Name, BaseType != null ? [BaseType] : [], [..EnumMembers], IsConst)
{
/// <inheritdoc/>
public override string DeclarationType => "enum";
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record InterfaceNode(
ImmutableArray<AttributeNode> Attributes,
string Name,
ImmutableArray<BaseTypeNode> BaseTypes,
ImmutableArray<MemberNode> Members,
bool IsConst = false) : TypeDeclarationNode(Attributes, Name, BaseTypes, Members, IsConst)
{
/// <inheritdoc/>
public override string DeclarationType => "interface";
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record UnionNode(
ImmutableArray<AttributeNode> Attributes,
string? Name,
ImmutableArray<BaseTypeNode> BaseTypes,
ImmutableArray<MemberNode> Members,
bool IsConst = false) : TypeDeclarationNode(Attributes, Name, BaseTypes, Members, IsConst)
{
/// <inheritdoc/>
public override string DeclarationType => "union";
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record StructNode(
ImmutableArray<AttributeNode> Attributes,
string? Name,
ImmutableArray<BaseTypeNode> BaseTypes,
ImmutableArray<MemberNode> Members,
bool IsConst = false) : TypeDeclarationNode(Attributes, Name, BaseTypes, Members, IsConst)
{
/// <inheritdoc/>
public override string DeclarationType => "struct";
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record ClassNode(
ImmutableArray<AttributeNode> Attributes,
string? Name,
ImmutableArray<BaseTypeNode> BaseTypes,
ImmutableArray<MemberNode> Members,
bool IsConst = false) : TypeDeclarationNode(Attributes, Name, BaseTypes, Members, IsConst)
{
/// <inheritdoc/>
public override string DeclarationType => "class";
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>Represents a base type in a type hierarchy.</summary>
public sealed record BaseTypeNode(ImmutableArray<AttributeNode> Attributes, string Name) : SyntaxNode, IAttributableNode, INamedNode
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>Base class for nodes representing members of a type.</summary>
public abstract record MemberNode(ImmutableArray<AttributeNode> Attributes, string? Name, bool IsStatic = false) : SyntaxNode, IAttributableNode, INamedNode
{
}
public sealed record MemberBlockNode(ImmutableArray<AttributeNode> Attributes, ImmutableArray<MemberNode> Members) : MemberNode(Attributes, string.Empty, false)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>A syntax node representing a field on a type.</summary>
public sealed record FieldNode(ImmutableArray<AttributeNode> Attributes, string? Name, TypeNode Type, ExpressionNode? BitWidth, bool IsStatic = false) : MemberNode(Attributes, Name, IsStatic)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record MethodTypeNode(
TypeNode ReturnType,
ImmutableArray<ParameterNode> Parameters,
bool IsConst = false) : TypeNode(IsConst)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>A syntax node representing a method on a type.</summary>
public sealed record MethodNode(
ImmutableArray<AttributeNode> Attributes,
string Name,
MethodTypeNode Signature,
bool IsStatic = false,
bool ForceInline = false) : MemberNode(Attributes, Name, IsStatic)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>A dummy node representing the end of a member block, for member enumeration.</summary>
public sealed record MemberBlockEndNode(MemberBlockNode Block) : MemberNode([], null)
{
public override void Accept(ISyntaxVisitor visitor)
{
}
}
/// <summary>A syntax mode representing a method parameter.</summary>
public sealed record ParameterNode(ImmutableArray<AttributeNode> Attributes, TypeNode Type, string? Name) : SyntaxNode, IAttributableNode, INamedNode
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>Base class for all type reference nodes.</summary>
public abstract record TypeNode(bool IsConst = false) : SyntaxNode
{
}
/// <summary>A syntax node representing a reference to a named type.</summary>
public sealed record NamedTypeNode(string Name, bool IsConst = false) : TypeNode(IsConst), INamedNode
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public abstract record PointerOrReferenceTypeNode(TypeNode ElementType, bool IsConst = false) : TypeNode(IsConst)
{
}
/// <summary>A syntax node representing a typed pointer.</summary>
public sealed record PointerTypeNode(TypeNode ElementType, bool IsConst = false) : PointerOrReferenceTypeNode(ElementType, IsConst)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>A syntax node representing a typed reference.</summary>
public sealed record ReferenceTypeNode(TypeNode ElementType, bool IsConst = false) : PointerOrReferenceTypeNode(ElementType, IsConst)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record ArrayTypeNode(TypeNode ElementType, ExpressionNode? Length, bool IsConst = false) : TypeNode(IsConst)
{
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
/// <summary>Base class for all expression nodes.</summary>
public abstract record ExpressionNode : SyntaxNode
{
/// <summary>Evaluates a constant expression.</summary>
public abstract object Evaluate();
}
public abstract record LiteralNode : ExpressionNode
{
}
public sealed record StringLiteralNode(string Value) : LiteralNode
{
/// <inheritdoc/>
public override object Evaluate() => ToString();
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
/// <inheritdoc/>
public override string ToString() => Value[1..^1]; // TODO: escape chars
}
public sealed record IntegerLiteralNode(long Value) : LiteralNode
{
/// <inheritdoc/>
public override object Evaluate() => Value;
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public sealed record IdentifierExpressionNode(string Name) : ExpressionNode
{
/// <inheritdoc/>
public override object Evaluate() => Name;
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
public abstract record UnaryExpressionNode(ExpressionNode Operand) : ExpressionNode
{
}
public sealed record UnaryNegationNode(ExpressionNode Operand) : UnaryExpressionNode(Operand)
{
/// <inheritdoc/>
public override object Evaluate() => -(long)Operand.Evaluate();
/// <inheritdoc/>
public override void Accept(ISyntaxVisitor visitor) => visitor.Visit(this);
}
+111
View File
@@ -0,0 +1,111 @@
using XDLCompiler;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Immutable;
public static class SyntaxNodeExtensions
{
private static readonly Version s_Version0 = new(0, 0, 0, 0);
public static bool TryGetAttribute<TAttribute>(this IAttributableNode node, [NotNullWhen(true)] out TAttribute? attribute)
where TAttribute : class, IAttributeFactory<TAttribute>
{
foreach (var attributeNode in node.Attributes)
{
if (attributeNode.TryGetAttribute(out attribute))
{
return true;
}
}
attribute = null;
return false;
}
public static bool TryGetAttribute<TAttribute>(this AttributeNode node, [NotNullWhen(true)] out TAttribute? attribute)
where TAttribute : class, IAttributeFactory<TAttribute>
{
if (node.Name == TAttribute.Name)
{
attribute = TAttribute.Create(node);
return true;
}
attribute = null;
return false;
}
public static bool Exists(this IAttributableNode node, Version? version)
{
version ??= s_Version0;
if (node.TryGetAttribute(out AbiAddedAttribute? added) && added.Version > version)
return false;
if (node.TryGetAttribute(out AbiRemovedAttribute? removed) && removed.Version <= version)
return false;
return true;
}
public static IEnumerable<MemberNode> EnumerateAllMembers(this TypeDeclarationNode node, bool includeBlocks = false)
{
return EnumerateAllMembers(node.Members, includeBlocks);
}
public static IEnumerable<MemberNode> EnumerateMembers(this TypeDeclarationNode node, Version? abi, bool includeBlocks = false)
{
return EnumerateMembers(node.Members, abi, includeBlocks);
}
private static IEnumerable<MemberNode> EnumerateAllMembers(ImmutableArray<MemberNode> members, bool includeBlocks)
{
foreach (var member in members)
{
if (member is MemberBlockNode block)
{
if (includeBlocks)
yield return block;
foreach (var node in EnumerateAllMembers(block.Members, includeBlocks))
yield return node;
if (includeBlocks)
yield return new MemberBlockEndNode(block);
continue;
}
yield return member;
}
}
private static IEnumerable<MemberNode> EnumerateMembers(ImmutableArray<MemberNode> members, Version? abi, bool includeBlocks)
{
foreach (var member in members)
{
if (!member.Exists(abi))
continue;
if (member is MemberBlockNode block)
{
if (includeBlocks)
yield return block;
foreach (var node in EnumerateAllMembers(block.Members, includeBlocks))
{
if (!node.Exists(abi))
continue;
yield return node;
}
if (includeBlocks)
yield return new MemberBlockEndNode(block);
continue;
}
yield return member;
}
}
}

Some files were not shown because too many files have changed in this diff Show More