Skip to content

Commit

Permalink
feat: Add Constant Conversion Helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
furesoft committed Nov 6, 2024
1 parent e1e8c98 commit 65e80a3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Source/Silverfly.Backend/AstNodeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using DistIL.IR;
using Silverfly.Nodes;

namespace Silverfly.Backend;

public static class AstNodeExtensions
{
public static Value? ToConstant(this AstNode astNode)
{
if (astNode is LiteralNode literalNode)
{
return literalNode.Value switch
{
bool b => ConstInt.CreateI(b ? 1 : 0),
char ch => ConstInt.CreateI(ch),
byte b => ConstInt.CreateI(b),
short s => ConstInt.CreateI(s),
int i => ConstInt.CreateI(i),
long l => ConstInt.CreateL(l),

sbyte sb => ConstInt.CreateI(sb),
ushort us => ConstInt.CreateI(us),

float f => ConstFloat.CreateS(f),
double d => ConstFloat.CreateD(d),

string s => ConstString.Create(s),

null => ConstNull.Create(),
_ => throw new ArgumentOutOfRangeException()
};
}

return null;
}


public static BinaryOp MapBinOperator(string op) =>
op switch
{
"+" => BinaryOp.Add,
"-" => BinaryOp.Sub,
"*" => BinaryOp.Mul,
"/" => BinaryOp.FDiv,
_ => throw new ArgumentOutOfRangeException(nameof(op), op, null)
};
}
1 change: 1 addition & 0 deletions Source/Silverfly.Backend/Silverfly.Backend.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<TargetFramework>net8.0</TargetFramework>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<IsTrimmable>true</IsTrimmable>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand Down

0 comments on commit 65e80a3

Please sign in to comment.