Compare commits
118 Commits
ec422cf1cd
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa5a494d39 | ||
|
|
bc65c3f4fd | ||
|
|
bdeb2c4d73 | ||
|
|
48760dcdda | ||
|
|
63d0eb660b | ||
|
|
918d25f8c8 | ||
|
|
6e631ba1ba | ||
|
|
832184053f | ||
|
|
2ab20652f8 | ||
|
|
6507624e90 | ||
|
|
83255980d7 | ||
|
|
1a1dc1389d | ||
|
|
4210ad878b | ||
|
|
32042d0769 | ||
|
|
dd44e3edc4 | ||
|
|
24d41d3dcb | ||
|
|
c9bf212aa2 | ||
|
|
0e099d0baf | ||
|
|
0be4e35628 | ||
|
|
7dd635fa91 | ||
|
|
693b119781 | ||
|
|
2b7eb56895 | ||
|
|
5f4a4172bf | ||
|
|
9da370e387 | ||
|
|
faf506f409 | ||
|
|
16d27c76ab | ||
|
|
270be1f740 | ||
|
|
da2fa81c39 | ||
|
|
677c7dea9e | ||
|
|
6ba05d00d7 | ||
|
|
d58e006be4 | ||
|
|
84627dde45 | ||
|
|
e7aad861d3 | ||
|
|
ecb628c4c2 | ||
|
|
e5227f7a99 | ||
|
|
73ecbf8e9b | ||
|
|
e512650440 | ||
|
|
272ea33616 | ||
|
|
b7dc77cb1c | ||
|
|
3323d760e8 | ||
|
|
aa5bf0b568 | ||
|
|
660166221c | ||
|
|
49734544e6 | ||
|
|
cb4aeb9c01 | ||
|
|
d771396bd4 | ||
|
|
7b1e202424 | ||
|
|
282dd0502a | ||
|
|
3ebaa67b6d | ||
|
|
35867ffa28 | ||
|
|
76efc84984 | ||
|
|
583c01201f | ||
|
|
1511d5d2b8 | ||
|
|
caa3b378b3 | ||
|
|
cbe27c0ae8 | ||
|
|
4d0f7c715f | ||
|
|
c342b2e102 | ||
|
|
ee485e4119 | ||
|
|
21a095f691 | ||
|
|
0a5b39b217 | ||
|
|
ab2f5750dc | ||
|
|
b45a0fa8cc | ||
|
|
7daccba9f3 | ||
|
|
924bdae89b | ||
|
|
5364b0420a | ||
|
|
c65fbeba13 | ||
|
|
9d8d8f255a | ||
|
|
576abe1240 | ||
|
|
d0c31ad17f | ||
|
|
7872a4b6b8 | ||
|
|
6ae10d5f90 | ||
|
|
d3e2dcede8 | ||
|
|
88fe03c048 | ||
|
|
9ccdd5f835 | ||
|
|
b7cfdd2519 | ||
|
|
d409bb4d92 | ||
|
|
00a172b922 | ||
|
|
ea3d374831 | ||
|
|
ab9bd6fd05 | ||
|
|
96670b1201 | ||
|
|
9fb9c50a0b | ||
|
|
89a827fdef | ||
|
|
f035499ba7 | ||
|
|
3e3757a402 | ||
|
|
1d63bd6389 | ||
|
|
1a3cf3c4fd | ||
|
|
5105a689df | ||
|
|
bd7e3fc931 | ||
| 3b89b3d9bb | |||
| 3db412a060 | |||
| b31a2d01c6 | |||
| 6f03e2203f | |||
| e20f6cd7af | |||
| 00714ea4b0 | |||
| 4761cd1f83 | |||
| 423ec4c798 | |||
| 38f55d8e7c | |||
| 1a5742fc4f | |||
| 4c201c4085 | |||
| e77c7028b9 | |||
| 26d365cf4f | |||
| f2ea00b34d | |||
| cb2411a7eb | |||
| 3b75e62aa7 | |||
|
|
3f18aa4782 | ||
|
|
3505e2547a | ||
|
|
766ca9a6b9 | ||
|
|
a5f73a84cc | ||
|
|
e294a26834 | ||
|
|
0c35bc052c | ||
|
|
2641357832 | ||
|
|
9f91e42d63 | ||
|
|
a7c45784b9 | ||
|
|
7486f2fd4e | ||
|
|
6775a09ba9 | ||
|
|
0f191b21bc | ||
|
|
bfe8b7b18e | ||
|
|
db5d444cf2 | ||
|
|
08ae39b5ed |
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
import os
|
||||
import clang.cindex
|
||||
from clang.cindex import CursorKind, TypeKind, Type
|
||||
|
||||
|
||||
def map_type(clang_type: Type):
|
||||
canonical = clang_type.get_canonical()
|
||||
kind = canonical.kind
|
||||
spelling = (
|
||||
canonical.spelling.replace("const ", "")
|
||||
.replace("volatile ", "")
|
||||
.replace("restrict ", "")
|
||||
.replace("struct ", "")
|
||||
.replace("union ", "")
|
||||
)
|
||||
|
||||
if kind == TypeKind.POINTER:
|
||||
pointee = canonical.get_pointee()
|
||||
if pointee.kind == TypeKind.RECORD:
|
||||
decl = pointee.get_declaration()
|
||||
if not decl.is_definition():
|
||||
return "^void"
|
||||
|
||||
if pointee.kind == TypeKind.CHAR_S or pointee.kind == TypeKind.CHAR_U:
|
||||
return "cstring"
|
||||
|
||||
if pointee.kind == TypeKind.FUNCTIONPROTO:
|
||||
arg_types = []
|
||||
|
||||
for arg in pointee.get_canonical().argument_types():
|
||||
arg_types.append(map_type(arg))
|
||||
|
||||
mapped_return = map_type(pointee.get_canonical().get_result())
|
||||
args_str = ", ".join(arg_types)
|
||||
|
||||
return f"func({args_str}): {mapped_return}"
|
||||
|
||||
return f"^{map_type(pointee)}"
|
||||
|
||||
if kind == TypeKind.CONSTANTARRAY:
|
||||
element_type = canonical.get_array_element_type()
|
||||
size = canonical.get_array_size()
|
||||
return f"[{size}]{map_type(element_type)}"
|
||||
|
||||
if kind == TypeKind.INCOMPLETEARRAY:
|
||||
element_type = canonical.get_array_element_type()
|
||||
return f"[?]{map_type(element_type)}"
|
||||
|
||||
if kind == TypeKind.FUNCTIONPROTO or kind == TypeKind.FUNCTIONNOPROTO:
|
||||
arg_types = []
|
||||
|
||||
for arg in canonical.argument_types():
|
||||
arg_types.append(map_type(arg))
|
||||
|
||||
mapped_return = map_type(canonical.get_result())
|
||||
args_str = ", ".join(arg_types)
|
||||
|
||||
return f"func({args_str}): {mapped_return}"
|
||||
|
||||
if kind == TypeKind.VOID:
|
||||
return "void"
|
||||
|
||||
if kind == TypeKind.BOOL:
|
||||
return "bool"
|
||||
|
||||
if kind in [TypeKind.CHAR_S, TypeKind.SCHAR]:
|
||||
return "i8"
|
||||
if kind == TypeKind.CHAR_U or kind == TypeKind.UCHAR:
|
||||
return "u8"
|
||||
if kind == TypeKind.SHORT:
|
||||
return "i16"
|
||||
if kind == TypeKind.USHORT:
|
||||
return "u16"
|
||||
if kind == TypeKind.INT:
|
||||
return "i32"
|
||||
if kind == TypeKind.UINT:
|
||||
return "u32"
|
||||
if kind in [TypeKind.LONG, TypeKind.LONGLONG]:
|
||||
return "i64"
|
||||
if kind in [TypeKind.ULONG, TypeKind.ULONGLONG]:
|
||||
return "u64"
|
||||
|
||||
if kind == TypeKind.FLOAT:
|
||||
return "f32"
|
||||
if kind == TypeKind.DOUBLE or kind == TypeKind.LONGDOUBLE:
|
||||
return "f64"
|
||||
|
||||
if kind == TypeKind.RECORD:
|
||||
return spelling
|
||||
|
||||
raise Exception(f"Unresolved type: {spelling}")
|
||||
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python3 generate.py [path to header]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
filename = sys.argv[1]
|
||||
|
||||
index = clang.cindex.Index.create()
|
||||
|
||||
tu = index.parse(filename, ["-x", "c", "-std=c23", "-I/usr/include"])
|
||||
|
||||
if tu.diagnostics:
|
||||
for diag in tu.diagnostics:
|
||||
if diag.severity >= clang.cindex.Diagnostic.Error:
|
||||
print(f"Error: {diag.spelling}", file=sys.stderr)
|
||||
|
||||
print(f'module "{os.path.basename(filename).split(".")[0]}"')
|
||||
print()
|
||||
|
||||
seen_structs = []
|
||||
|
||||
for cursor in tu.cursor.walk_preorder():
|
||||
if cursor.location.file and cursor.location.file.name != filename:
|
||||
continue
|
||||
|
||||
if cursor.kind == CursorKind.FUNCTION_DECL:
|
||||
name = cursor.spelling
|
||||
return_type = map_type(cursor.result_type)
|
||||
|
||||
params = []
|
||||
for arg in cursor.get_arguments():
|
||||
param_name = arg.spelling
|
||||
param_type = map_type(arg.type)
|
||||
params.append(f"{param_name}: {param_type}")
|
||||
|
||||
params_str = ", ".join(params)
|
||||
|
||||
print(f'export extern "{name}" func {name}({params_str}): {return_type}')
|
||||
|
||||
elif cursor.kind == CursorKind.STRUCT_DECL:
|
||||
if cursor.get_usr() in seen_structs:
|
||||
continue
|
||||
|
||||
seen_structs.append(cursor.get_usr())
|
||||
|
||||
if cursor.is_definition():
|
||||
name = cursor.spelling
|
||||
print(f"export struct {name}")
|
||||
print("{")
|
||||
for field in cursor.get_children():
|
||||
if field.kind == CursorKind.FIELD_DECL:
|
||||
field_name = field.spelling
|
||||
field_type = map_type(field.type)
|
||||
print(f" {field_name}: {field_type}")
|
||||
else:
|
||||
raise Exception(
|
||||
f"Unsupported child of struct: {field.spelling}: {field.kind}"
|
||||
)
|
||||
print("}")
|
||||
|
||||
elif cursor.kind == CursorKind.ENUM_DECL:
|
||||
name = cursor.spelling
|
||||
print(f"export enum {name} : u32")
|
||||
print("{")
|
||||
for field in cursor.get_children():
|
||||
if field.kind == CursorKind.ENUM_CONSTANT_DECL:
|
||||
field_name = field.spelling
|
||||
field_value = field.enum_value
|
||||
print(f" {field_name} = {field_value}")
|
||||
else:
|
||||
raise Exception(
|
||||
f"Unsupported child of enum: {field.spelling}: {field.kind}"
|
||||
)
|
||||
print("}")
|
||||
38
compiler/.gitignore
vendored
38
compiler/.gitignore
vendored
@@ -1,34 +1,4 @@
|
||||
# Common IntelliJ Platform excludes
|
||||
|
||||
# User specific
|
||||
**/.idea/**/workspace.xml
|
||||
**/.idea/**/tasks.xml
|
||||
**/.idea/shelf/*
|
||||
**/.idea/dictionaries
|
||||
**/.idea/httpRequests/
|
||||
|
||||
# Sensitive or high-churn files
|
||||
**/.idea/**/dataSources/
|
||||
**/.idea/**/dataSources.ids
|
||||
**/.idea/**/dataSources.xml
|
||||
**/.idea/**/dataSources.local.xml
|
||||
**/.idea/**/sqlDataSources.xml
|
||||
**/.idea/**/dynamic.xml
|
||||
|
||||
# Rider
|
||||
# Rider auto-generates .iml files, and contentModel.xml
|
||||
**/.idea/**/*.iml
|
||||
**/.idea/**/contentModel.xml
|
||||
**/.idea/**/modules.xml
|
||||
|
||||
*.suo
|
||||
*.user
|
||||
.vs/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
_UpgradeReport_Files/
|
||||
[Pp]ackages/
|
||||
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
.DS_Store
|
||||
.idea
|
||||
bin
|
||||
obj
|
||||
.build
|
||||
13
compiler/.idea/.idea.Compiler/.idea/.gitignore
generated
vendored
13
compiler/.idea/.idea.Compiler/.idea/.gitignore
generated
vendored
@@ -1,13 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Rider ignored files
|
||||
/modules.xml
|
||||
/projectSettingsUpdater.xml
|
||||
/contentModel.xml
|
||||
/.idea.Compiler.iml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
1
compiler/.idea/.idea.Compiler/.idea/.name
generated
1
compiler/.idea/.idea.Compiler/.idea/.name
generated
@@ -1 +0,0 @@
|
||||
Compiler
|
||||
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
|
||||
</project>
|
||||
10
compiler/.idea/.idea.Compiler/.idea/indexLayout.xml
generated
10
compiler/.idea/.idea.Compiler/.idea/indexLayout.xml
generated
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="UserContentModel">
|
||||
<attachedFolders>
|
||||
<Path>Runtime</Path>
|
||||
</attachedFolders>
|
||||
<explicitIncludes />
|
||||
<explicitExcludes />
|
||||
</component>
|
||||
</project>
|
||||
6
compiler/.idea/.idea.Compiler/.idea/vcs.xml
generated
6
compiler/.idea/.idea.Compiler/.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,10 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsAotCompatible>true</IsAotCompatible>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,28 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NubLang", "NubLang\NubLang.csproj", "{5047E21F-590D-4CB3-AFF3-064316485009}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NubLang.CLI", "NubLang.CLI\NubLang.CLI.csproj", "{A22F17ED-FA17-45AB-92BA-CD02C28B3524}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NubLang.LSP", "NubLang.LSP\NubLang.LSP.csproj", "{07968F84-0C2E-4D2E-8905-DC8A6140B4C0}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{5047E21F-590D-4CB3-AFF3-064316485009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5047E21F-590D-4CB3-AFF3-064316485009}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5047E21F-590D-4CB3-AFF3-064316485009}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5047E21F-590D-4CB3-AFF3-064316485009}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
173
compiler/Diagnostic.cs
Normal file
173
compiler/Diagnostic.cs
Normal file
@@ -0,0 +1,173 @@
|
||||
namespace Compiler;
|
||||
|
||||
public class Diagnostic
|
||||
{
|
||||
public static Builder Info(string message) => new Builder(DiagnosticSeverity.Info, message);
|
||||
public static Builder Warning(string message) => new Builder(DiagnosticSeverity.Warning, message);
|
||||
public static Builder Error(string message) => new Builder(DiagnosticSeverity.Error, message);
|
||||
|
||||
private Diagnostic(DiagnosticSeverity severity, string message, string? help, FileInfo? file)
|
||||
{
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Help = help;
|
||||
File = file;
|
||||
}
|
||||
|
||||
public class FileInfo(string file, int line, int column, int length)
|
||||
{
|
||||
public string File { get; } = file;
|
||||
public int Line { get; } = line;
|
||||
public int Column { get; } = column;
|
||||
public int Length { get; } = length;
|
||||
}
|
||||
|
||||
public DiagnosticSeverity Severity { get; }
|
||||
public string Message { get; }
|
||||
public string? Help { get; }
|
||||
public FileInfo? File { get; }
|
||||
|
||||
public enum DiagnosticSeverity
|
||||
{
|
||||
Info,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
public class Builder(DiagnosticSeverity severity, string message)
|
||||
{
|
||||
private FileInfo? file;
|
||||
private string? help;
|
||||
|
||||
public Builder At(string fileName, int line, int column, int length)
|
||||
{
|
||||
file = new FileInfo(fileName, line, column, length);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder At(string fileName, Token? token)
|
||||
{
|
||||
if (token != null)
|
||||
{
|
||||
At(fileName, token.Line, token.Column, token.Length);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder At(string fileName, Node? node)
|
||||
{
|
||||
if (node != null && node.Tokens.Count != 0)
|
||||
{
|
||||
// todo(nub31): Calculate length based on last token
|
||||
At(fileName, node.Tokens[0]);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder At(string fileName, TypedNode? node)
|
||||
{
|
||||
if (node != null && node.Tokens.Count != 0)
|
||||
{
|
||||
// todo(nub31): Calculate length based on last token
|
||||
At(fileName, node.Tokens[0]);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder WithHelp(string helpMessage)
|
||||
{
|
||||
help = helpMessage;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Diagnostic Build()
|
||||
{
|
||||
return new Diagnostic(severity, message, help, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class CompileException(Diagnostic diagnostic) : Exception
|
||||
{
|
||||
public Diagnostic Diagnostic { get; } = diagnostic;
|
||||
}
|
||||
|
||||
public static class DiagnosticFormatter
|
||||
{
|
||||
public static void Print(Diagnostic diagnostic, TextWriter writer)
|
||||
{
|
||||
var (label, color) = diagnostic.Severity switch
|
||||
{
|
||||
Diagnostic.DiagnosticSeverity.Info => ("info", Ansi.Cyan),
|
||||
Diagnostic.DiagnosticSeverity.Warning => ("warning", Ansi.Yellow),
|
||||
Diagnostic.DiagnosticSeverity.Error => ("error", Ansi.Red),
|
||||
_ => ("unknown", Ansi.Reset),
|
||||
};
|
||||
|
||||
writer.Write(color);
|
||||
writer.Write(label);
|
||||
writer.Write(Ansi.Reset);
|
||||
writer.Write(": ");
|
||||
writer.WriteLine(diagnostic.Message);
|
||||
|
||||
if (diagnostic.File is null)
|
||||
return;
|
||||
|
||||
var file = diagnostic.File;
|
||||
var lineNumberWidth = diagnostic.File.Line.ToString().Length;
|
||||
|
||||
writer.WriteLine($" {new string(' ', lineNumberWidth)}{file.File}:{file.Line}:{file.Column}");
|
||||
writer.WriteLine($"{new string(' ', lineNumberWidth)} | ");
|
||||
|
||||
var sourceLine = TryReadLine(file.File, file.Line);
|
||||
if (sourceLine != null)
|
||||
{
|
||||
writer.Write($"{file.Line.ToString().PadLeft(lineNumberWidth)} | ");
|
||||
writer.WriteLine(sourceLine);
|
||||
|
||||
writer.Write(new string(' ', lineNumberWidth));
|
||||
writer.Write(" | ");
|
||||
writer.Write(new string(' ', file.Column - 1));
|
||||
writer.Write(color);
|
||||
writer.Write(new string('^', Math.Max(1, file.Length)));
|
||||
writer.WriteLine(Ansi.Reset);
|
||||
}
|
||||
|
||||
writer.WriteLine($"{new string(' ', lineNumberWidth)} |");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(diagnostic.Help))
|
||||
{
|
||||
writer.WriteLine($" = help: {diagnostic.Help}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string? TryReadLine(string file, int line)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var reader = new StreamReader(file);
|
||||
for (var i = 1; i < line; i++)
|
||||
{
|
||||
if (reader.ReadLine() == null)
|
||||
return null;
|
||||
}
|
||||
|
||||
return reader.ReadLine();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static class Ansi
|
||||
{
|
||||
public const string Reset = "\e[0m";
|
||||
public const string Red = "\e[31m";
|
||||
public const string Yellow = "\e[33m";
|
||||
public const string Cyan = "\e[36m";
|
||||
}
|
||||
}
|
||||
1136
compiler/Generator.cs
Normal file
1136
compiler/Generator.cs
Normal file
File diff suppressed because it is too large
Load Diff
446
compiler/ModuleGraph.cs
Normal file
446
compiler/ModuleGraph.cs
Normal file
@@ -0,0 +1,446 @@
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
public class ModuleGraph
|
||||
{
|
||||
public static Builder CreateBuilder() => new();
|
||||
|
||||
private ModuleGraph(Dictionary<string, Module> modules)
|
||||
{
|
||||
this.modules = modules;
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, Module> modules;
|
||||
|
||||
public List<Module> GetModules()
|
||||
{
|
||||
return modules.Values.ToList();
|
||||
}
|
||||
|
||||
public bool TryResolveIdentifier(string moduleName, string identifierName, bool searchPrivate, [NotNullWhen(true)] out Module.IdentifierInfo? info)
|
||||
{
|
||||
if (!TryResolveModule(moduleName, out var module))
|
||||
{
|
||||
info = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!module.TryResolveIdentifier(identifierName, searchPrivate, out info))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryResolveType(string moduleName, string typeName, bool searchPrivate, [NotNullWhen(true)] out Module.TypeInfo? info)
|
||||
{
|
||||
if (!TryResolveModule(moduleName, out var module))
|
||||
{
|
||||
info = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!module.TryResolveType(typeName, searchPrivate, out info))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryResolveModule(string moduleName, [NotNullWhen(true)] out Module? module)
|
||||
{
|
||||
module = modules.GetValueOrDefault(moduleName);
|
||||
return module != null;
|
||||
}
|
||||
|
||||
public class Builder
|
||||
{
|
||||
private readonly List<Ast> asts = [];
|
||||
private readonly List<Manifest> manifests = [];
|
||||
|
||||
public void AddAst(Ast ast)
|
||||
{
|
||||
asts.Add(ast);
|
||||
}
|
||||
|
||||
public void AddManifest(Manifest manifest)
|
||||
{
|
||||
manifests.Add(manifest);
|
||||
}
|
||||
|
||||
public ModuleGraph? Build(out List<Diagnostic> diagnostics)
|
||||
{
|
||||
diagnostics = [];
|
||||
|
||||
var modules = new Dictionary<string, Module>();
|
||||
|
||||
foreach (var manifest in manifests)
|
||||
{
|
||||
foreach (var (moduleName, manifestModule) in manifest.Modules)
|
||||
{
|
||||
var module = GetOrCreateModule(moduleName);
|
||||
|
||||
foreach (var (name, type) in manifestModule.Types)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case Manifest.Module.TypeInfoStruct s:
|
||||
{
|
||||
var info = new Module.TypeInfoStruct(Module.DefinitionSource.Imported, s.Exported, s.Packed);
|
||||
var fields = s.Fields.Select(x => new Module.TypeInfoStruct.Field(x.Name, x.Type)).ToList();
|
||||
info.SetFields(fields);
|
||||
module.AddType(name, info);
|
||||
break;
|
||||
}
|
||||
case Manifest.Module.TypeInfoEnum e:
|
||||
{
|
||||
var info = new Module.TypeInfoEnum(Module.DefinitionSource.Imported, e.Exported);
|
||||
var variants = e.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name, v.Type)).ToList();
|
||||
info.SetVariants(variants);
|
||||
module.AddType(name, info);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(type));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (name, identifier) in manifestModule.Identifiers)
|
||||
{
|
||||
module.AddIdentifier(name, new Module.IdentifierInfo(Module.DefinitionSource.Imported, identifier.Exported, identifier.Extern, identifier.Type, identifier.MangledName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
var module = GetOrCreateModule(ast.ModuleName.Ident);
|
||||
|
||||
foreach (var structDef in ast.Definitions.OfType<NodeDefinitionStruct>())
|
||||
{
|
||||
module.AddType(structDef.Name.Ident, new Module.TypeInfoStruct(Module.DefinitionSource.Internal, structDef.Exported, structDef.Packed));
|
||||
}
|
||||
|
||||
foreach (var enumDef in ast.Definitions.OfType<NodeDefinitionEnum>())
|
||||
{
|
||||
module.AddType(enumDef.Name.Ident, new Module.TypeInfoEnum(Module.DefinitionSource.Internal, enumDef.Exported));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
var module = GetOrCreateModule(ast.ModuleName.Ident);
|
||||
|
||||
foreach (var structDef in ast.Definitions.OfType<NodeDefinitionStruct>())
|
||||
{
|
||||
if (!module.TryResolveType(structDef.Name.Ident, true, out var typeInfo))
|
||||
throw new UnreachableException($"{nameof(typeInfo)} should always be registered");
|
||||
|
||||
if (typeInfo is Module.TypeInfoStruct structType)
|
||||
{
|
||||
var fields = structDef.Fields.Select(f => new Module.TypeInfoStruct.Field(f.Name.Ident, ResolveType(f.Type, module.Name))).ToList();
|
||||
structType.SetFields(fields);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var enumDef in ast.Definitions.OfType<NodeDefinitionEnum>())
|
||||
{
|
||||
if (!module.TryResolveType(enumDef.Name.Ident, true, out var typeInfo))
|
||||
throw new UnreachableException($"{nameof(typeInfo)} should always be registered");
|
||||
|
||||
if (typeInfo is Module.TypeInfoEnum enumType)
|
||||
{
|
||||
var variants = enumDef.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name.Ident, v.Type == null ? null : ResolveType(v.Type, module.Name))).ToList();
|
||||
enumType.SetVariants(variants);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
var module = GetOrCreateModule(ast.ModuleName.Ident);
|
||||
|
||||
foreach (var funcDef in ast.Definitions.OfType<NodeDefinitionFunc>())
|
||||
{
|
||||
var parameters = funcDef.Parameters.Select(x => ResolveType(x.Type, module.Name)).ToList();
|
||||
var returnType = funcDef.ReturnType == null ? NubTypeVoid.Instance : ResolveType(funcDef.ReturnType, module.Name);
|
||||
var funcType = NubTypeFunc.Get(parameters, returnType);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, funcDef.Exported, false, funcType, NameMangler.Mangle(module.Name, funcDef.Name.Ident, funcType));
|
||||
module.AddIdentifier(funcDef.Name.Ident, info);
|
||||
}
|
||||
|
||||
foreach (var funcDef in ast.Definitions.OfType<NodeDefinitionExternFunc>())
|
||||
{
|
||||
var parameters = funcDef.Parameters.Select(x => ResolveType(x.Type, module.Name)).ToList();
|
||||
var returnType = funcDef.ReturnType == null ? NubTypeVoid.Instance : ResolveType(funcDef.ReturnType, module.Name);
|
||||
var funcType = NubTypeFunc.Get(parameters, returnType);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, funcDef.Exported, true, funcType, funcDef.Name.Ident);
|
||||
module.AddIdentifier(funcDef.Name.Ident, info);
|
||||
}
|
||||
|
||||
foreach (var globalVariable in ast.Definitions.OfType<NodeDefinitionGlobalVariable>())
|
||||
{
|
||||
var type = ResolveType(globalVariable.Type, module.Name);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, globalVariable.Exported, false, type, NameMangler.Mangle(module.Name, globalVariable.Name.Ident, type));
|
||||
module.AddIdentifier(globalVariable.Name.Ident, info);
|
||||
}
|
||||
|
||||
foreach (var globalVariable in ast.Definitions.OfType<NodeDefinitionExternGlobalVariable>())
|
||||
{
|
||||
var type = ResolveType(globalVariable.Type, module.Name);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, globalVariable.Exported, true, type, NameMangler.Mangle(module.Name, globalVariable.Name.Ident, type));
|
||||
module.AddIdentifier(globalVariable.Name.Ident, info);
|
||||
}
|
||||
}
|
||||
|
||||
if (diagnostics.Any(x => x.Severity == Diagnostic.DiagnosticSeverity.Error))
|
||||
return null;
|
||||
|
||||
return new ModuleGraph(modules);
|
||||
|
||||
NubType ResolveType(NodeType node, string currentModule)
|
||||
{
|
||||
return node switch
|
||||
{
|
||||
NodeTypeBool => NubTypeBool.Instance,
|
||||
NodeTypeNamed type => ResolveNamedType(type, currentModule),
|
||||
NodeTypeAnonymousStruct type => NubTypeAnonymousStruct.Get(type.Fields.Select(x => new NubTypeAnonymousStruct.Field(x.Name.Ident, ResolveType(x.Type, currentModule))).ToList()),
|
||||
NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(x => ResolveType(x, currentModule)).ToList(), ResolveType(type.ReturnType, currentModule)),
|
||||
NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To, currentModule)),
|
||||
NodeTypeSInt type => NubTypeSInt.Get(type.Width),
|
||||
NodeTypeUInt type => NubTypeUInt.Get(type.Width),
|
||||
NodeTypeString => NubTypeString.Instance,
|
||||
NodeTypeChar => NubTypeChar.Instance,
|
||||
NodeTypeVoid => NubTypeVoid.Instance,
|
||||
NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType, currentModule)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
}
|
||||
|
||||
NubType ResolveNamedType(NodeTypeNamed type, string currentModule)
|
||||
{
|
||||
return type.Sections.Count switch
|
||||
{
|
||||
3 => ResolveThreePartType(type.Sections[0], type.Sections[1], type.Sections[2], currentModule),
|
||||
2 => ResolveTwoPartType(type.Sections[0], type.Sections[1], currentModule),
|
||||
1 => ResolveOnePartType(type.Sections[0], currentModule),
|
||||
_ => throw BasicError("Invalid type name")
|
||||
};
|
||||
}
|
||||
|
||||
NubType ResolveThreePartType(TokenIdent first, TokenIdent second, TokenIdent third, string currentModule)
|
||||
{
|
||||
var module = ResolveModule(first);
|
||||
if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo))
|
||||
throw BasicError($"Named type '{module.Name}::{second.Ident}' not found");
|
||||
|
||||
if (typeInfo is not Module.TypeInfoEnum enumInfo)
|
||||
throw BasicError($"'{module.Name}::{second.Ident}' is not an enum");
|
||||
|
||||
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == third.Ident);
|
||||
if (variant == null)
|
||||
throw BasicError($"Enum '{module.Name}::{second.Ident}' does not have a variant named '{third.Ident}'");
|
||||
|
||||
return NubTypeEnumVariant.Get(NubTypeEnum.Get(module.Name, second.Ident), third.Ident);
|
||||
}
|
||||
|
||||
NubType ResolveTwoPartType(TokenIdent first, TokenIdent second, string currentModule)
|
||||
{
|
||||
if (TryResolveEnumVariant(currentModule, first.Ident, second.Ident, out var variant))
|
||||
return variant;
|
||||
|
||||
var module = ResolveModule(first);
|
||||
if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo))
|
||||
throw BasicError($"Named type '{module.Name}::{second.Ident}' not found");
|
||||
|
||||
return typeInfo switch
|
||||
{
|
||||
Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, second.Ident),
|
||||
Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, second.Ident),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||
};
|
||||
}
|
||||
|
||||
NubType ResolveOnePartType(TokenIdent name, string currentModule)
|
||||
{
|
||||
if (!modules.TryGetValue(currentModule, out var module))
|
||||
throw BasicError($"Module '{currentModule}' not found");
|
||||
|
||||
if (!module.TryResolveType(name.Ident, true, out var typeInfo))
|
||||
throw BasicError($"Named type '{module.Name}::{name.Ident}' not found");
|
||||
|
||||
return typeInfo switch
|
||||
{
|
||||
Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, name.Ident),
|
||||
Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, name.Ident),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||
};
|
||||
}
|
||||
|
||||
Module ResolveModule(TokenIdent name)
|
||||
{
|
||||
if (!modules.TryGetValue(name.Ident, out var module))
|
||||
throw BasicError($"Module '{name.Ident}' not found");
|
||||
|
||||
return module;
|
||||
}
|
||||
|
||||
bool TryResolveEnumVariant(string moduleName, string enumName, string variantName, [NotNullWhen(true)] out NubType? result)
|
||||
{
|
||||
result = null;
|
||||
|
||||
if (!modules.TryGetValue(moduleName, out var module))
|
||||
return false;
|
||||
|
||||
if (!module.TryResolveType(enumName, true, out var typeInfo))
|
||||
return false;
|
||||
|
||||
if (typeInfo is not Module.TypeInfoEnum enumInfo)
|
||||
return false;
|
||||
|
||||
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == variantName);
|
||||
if (variant == null)
|
||||
return false;
|
||||
|
||||
result = NubTypeEnumVariant.Get(
|
||||
NubTypeEnum.Get(moduleName, enumName),
|
||||
variantName);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Exception BasicError(string message)
|
||||
{
|
||||
return new CompileException(Diagnostic.Error(message).Build());
|
||||
}
|
||||
|
||||
Module GetOrCreateModule(string name)
|
||||
{
|
||||
if (!modules.TryGetValue(name, out var module))
|
||||
{
|
||||
module = new Module(name);
|
||||
modules.Add(name, module);
|
||||
}
|
||||
|
||||
return module;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Module(string name)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
|
||||
private Dictionary<string, TypeInfo> types = new();
|
||||
private Dictionary<string, IdentifierInfo> identifiers = new();
|
||||
|
||||
public IReadOnlyDictionary<string, TypeInfo> GetTypes() => types;
|
||||
public IReadOnlyDictionary<string, IdentifierInfo> GetIdentifiers() => identifiers;
|
||||
|
||||
public bool TryResolveType(string name, bool searchPrivate, [NotNullWhen(true)] out TypeInfo? customType)
|
||||
{
|
||||
var info = types.GetValueOrDefault(name);
|
||||
if (info == null)
|
||||
{
|
||||
customType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (searchPrivate || info.Source == DefinitionSource.Internal)
|
||||
{
|
||||
customType = info;
|
||||
return true;
|
||||
}
|
||||
|
||||
customType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveIdentifier(string name, bool searchPrivate, [NotNullWhen(true)] out IdentifierInfo? identifierType)
|
||||
{
|
||||
var info = identifiers.GetValueOrDefault(name);
|
||||
if (info == null)
|
||||
{
|
||||
identifierType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (searchPrivate || info.Source == DefinitionSource.Internal)
|
||||
{
|
||||
identifierType = info;
|
||||
return true;
|
||||
}
|
||||
|
||||
identifierType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void AddType(string name, TypeInfo info)
|
||||
{
|
||||
types.Add(name, info);
|
||||
}
|
||||
|
||||
public void AddIdentifier(string name, IdentifierInfo info)
|
||||
{
|
||||
identifiers.Add(name, info);
|
||||
}
|
||||
|
||||
public enum DefinitionSource
|
||||
{
|
||||
Internal,
|
||||
Imported,
|
||||
}
|
||||
|
||||
public class IdentifierInfo(DefinitionSource source, bool exported, bool @extern, NubType type, string mangledName)
|
||||
{
|
||||
public DefinitionSource Source { get; } = source;
|
||||
public bool Exported { get; } = exported;
|
||||
public bool Extern { get; } = @extern;
|
||||
public NubType Type { get; } = type;
|
||||
public string MangledName { get; } = mangledName;
|
||||
}
|
||||
|
||||
public abstract class TypeInfo(DefinitionSource source, bool exported)
|
||||
{
|
||||
public DefinitionSource Source { get; } = source;
|
||||
public bool Exported { get; } = exported;
|
||||
}
|
||||
|
||||
public class TypeInfoStruct(DefinitionSource source, bool exported, bool packed) : TypeInfo(source, exported)
|
||||
{
|
||||
private IReadOnlyList<Field>? fields;
|
||||
|
||||
public bool Packed { get; } = packed;
|
||||
public IReadOnlyList<Field> Fields => fields ?? throw new InvalidOperationException("Fields has not been set yet");
|
||||
|
||||
public void SetFields(IReadOnlyList<Field> fields)
|
||||
{
|
||||
this.fields = fields;
|
||||
}
|
||||
|
||||
public class Field(string name, NubType type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType Type { get; } = type;
|
||||
}
|
||||
}
|
||||
|
||||
public class TypeInfoEnum(DefinitionSource source, bool exported) : TypeInfo(source, exported)
|
||||
{
|
||||
private IReadOnlyList<Variant>? variants;
|
||||
|
||||
public IReadOnlyList<Variant> Variants => variants ?? throw new InvalidOperationException("Fields has not been set yet");
|
||||
|
||||
public void SetVariants(IReadOnlyList<Variant> variants)
|
||||
{
|
||||
this.variants = variants;
|
||||
}
|
||||
|
||||
public class Variant(string name, NubType? type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType? Type { get; } = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>nubc</AssemblyName>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\NubLang\NubLang.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,91 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using NubLang.Ast;
|
||||
using NubLang.Diagnostics;
|
||||
using NubLang.Generation;
|
||||
using NubLang.Syntax;
|
||||
|
||||
var diagnostics = new List<Diagnostic>();
|
||||
var syntaxTrees = new List<SyntaxTree>();
|
||||
|
||||
foreach (var file in args)
|
||||
{
|
||||
var tokenizer = new Tokenizer(file, File.ReadAllText(file));
|
||||
tokenizer.Tokenize();
|
||||
diagnostics.AddRange(tokenizer.Diagnostics);
|
||||
|
||||
var parser = new Parser();
|
||||
var syntaxTree = parser.Parse(tokenizer.Tokens);
|
||||
diagnostics.AddRange(parser.Diagnostics);
|
||||
|
||||
syntaxTrees.Add(syntaxTree);
|
||||
}
|
||||
|
||||
var modules = Module.Collect(syntaxTrees);
|
||||
var compilationUnits = new List<CompilationUnit>();
|
||||
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var typeChecker = new TypeChecker(syntaxTrees[i], modules);
|
||||
var compilationUnit = typeChecker.Check();
|
||||
|
||||
compilationUnits.Add(compilationUnit);
|
||||
diagnostics.AddRange(typeChecker.Diagnostics);
|
||||
}
|
||||
|
||||
foreach (var diagnostic in diagnostics)
|
||||
{
|
||||
Console.Error.WriteLine(diagnostic.FormatANSI());
|
||||
}
|
||||
|
||||
if (diagnostics.Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
var cPaths = new List<string>();
|
||||
|
||||
Directory.CreateDirectory(".build");
|
||||
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var file = args[i];
|
||||
var compilationUnit = compilationUnits[i];
|
||||
|
||||
var generator = new Generator(compilationUnit);
|
||||
var directory = Path.GetDirectoryName(file);
|
||||
if (!string.IsNullOrWhiteSpace(directory))
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(".build", directory));
|
||||
}
|
||||
|
||||
var path = Path.Combine(".build", Path.ChangeExtension(file, "c"));
|
||||
File.WriteAllText(path, generator.Emit());
|
||||
cPaths.Add(path);
|
||||
}
|
||||
|
||||
var objectPaths = new List<string>();
|
||||
|
||||
foreach (var cPath in cPaths)
|
||||
{
|
||||
var objectPath = Path.ChangeExtension(cPath, "o");
|
||||
using var compileProcess = Process.Start("clang", [
|
||||
"-ffreestanding", "-std=c23",
|
||||
"-g", "-c",
|
||||
"-o", objectPath,
|
||||
cPath,
|
||||
]);
|
||||
|
||||
compileProcess.WaitForExit();
|
||||
|
||||
if (compileProcess.ExitCode != 0)
|
||||
{
|
||||
Console.Error.WriteLine($"clang failed with exit code {compileProcess.ExitCode}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
objectPaths.Add(objectPath);
|
||||
}
|
||||
|
||||
Console.Out.WriteLine(string.Join(' ', objectPaths));
|
||||
|
||||
return 0;
|
||||
@@ -1,435 +0,0 @@
|
||||
using NubLang.Ast;
|
||||
using NubLang.Syntax;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
|
||||
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
public static class AstExtensions
|
||||
{
|
||||
public static Location ToLocation(this Node node)
|
||||
{
|
||||
if (node.Tokens.Count == 0)
|
||||
{
|
||||
return new Location();
|
||||
}
|
||||
|
||||
return new Location
|
||||
{
|
||||
Uri = node.Tokens.First().Span.FilePath,
|
||||
Range = new Range(node.Tokens.First().Span.Start.Line - 1, node.Tokens.First().Span.Start.Column - 1, node.Tokens.Last().Span.End.Line - 1, node.Tokens.Last().Span.End.Column - 1)
|
||||
};
|
||||
}
|
||||
|
||||
public static bool ContainsPosition(this Node node, int line, int character)
|
||||
{
|
||||
if (node.Tokens.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var start = node.Tokens.First().Span.Start;
|
||||
var end = node.Tokens.Last().Span.End;
|
||||
|
||||
var startLine = start.Line - 1;
|
||||
var startChar = start.Column - 1;
|
||||
var endLine = end.Line - 1;
|
||||
var endChar = end.Column - 1;
|
||||
|
||||
if (line < startLine || line > endLine) return false;
|
||||
|
||||
if (line > startLine && line < endLine) return true;
|
||||
|
||||
if (startLine == endLine)
|
||||
{
|
||||
return character >= startChar && character <= endChar;
|
||||
}
|
||||
|
||||
if (line == startLine)
|
||||
{
|
||||
return character >= startChar;
|
||||
}
|
||||
|
||||
if (line == endLine)
|
||||
{
|
||||
return character <= endChar;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static FuncNode? FunctionAtPosition(this CompilationUnit compilationUnit, int line, int character)
|
||||
{
|
||||
return compilationUnit
|
||||
.Functions
|
||||
.FirstOrDefault(x => x.ContainsPosition(line, character));
|
||||
}
|
||||
|
||||
public static Node? DeepestNodeAtPosition(this CompilationUnit compilationUnit, int line, int character)
|
||||
{
|
||||
return compilationUnit.Functions
|
||||
.SelectMany(x => x.EnumerateDescendantsAndSelf())
|
||||
.Where(n => n.ContainsPosition(line, character))
|
||||
.OrderBy(n => n.Tokens.First().Span.Start.Line)
|
||||
.ThenBy(n => n.Tokens.First().Span.Start.Column)
|
||||
.LastOrDefault();
|
||||
}
|
||||
|
||||
public static Node? DeepestNodeAtPosition(this Node node, int line, int character)
|
||||
{
|
||||
return node.EnumerateDescendantsAndSelf()
|
||||
.Where(n => n.ContainsPosition(line, character))
|
||||
.OrderBy(n => n.Tokens.First().Span.Start.Line)
|
||||
.ThenBy(n => n.Tokens.First().Span.Start.Column)
|
||||
.LastOrDefault();
|
||||
}
|
||||
|
||||
public static IEnumerable<Node> EnumerateDescendantsAndSelf(this Node node)
|
||||
{
|
||||
yield return node;
|
||||
|
||||
switch (node)
|
||||
{
|
||||
case FuncNode func:
|
||||
{
|
||||
foreach (var n in func.Prototype.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
if (func.Body != null)
|
||||
{
|
||||
foreach (var n in func.Body.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case FuncPrototypeNode proto:
|
||||
{
|
||||
foreach (var n in proto.Parameters.SelectMany(param => param.EnumerateDescendantsAndSelf()))
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case BlockNode block:
|
||||
{
|
||||
foreach (var n in block.Statements.SelectMany(stmt => stmt.EnumerateDescendantsAndSelf()))
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case StatementFuncCallNode stmtCall:
|
||||
{
|
||||
foreach (var n in stmtCall.FuncCall.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ReturnNode { Value: not null } ret:
|
||||
{
|
||||
foreach (var n in ret.Value.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case AssignmentNode assign:
|
||||
{
|
||||
foreach (var n in assign.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in assign.Value.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case IfNode ifNode:
|
||||
{
|
||||
foreach (var n in ifNode.Condition.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in ifNode.Body.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
if (ifNode.Else.HasValue)
|
||||
{
|
||||
if (ifNode.Else.Value.IsCase1(out var elseIfNode))
|
||||
{
|
||||
foreach (var n in elseIfNode.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
}
|
||||
else if (ifNode.Else.Value.IsCase2(out var elseNode))
|
||||
{
|
||||
foreach (var n in elseNode.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case VariableDeclarationNode decl:
|
||||
{
|
||||
if (decl.Assignment != null)
|
||||
{
|
||||
foreach (var n in decl.Assignment.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case WhileNode whileNode:
|
||||
{
|
||||
foreach (var n in whileNode.Condition.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in whileNode.Body.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ForSliceNode forSlice:
|
||||
{
|
||||
foreach (var n in forSlice.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in forSlice.Body.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ForConstArrayNode forConst:
|
||||
{
|
||||
foreach (var n in forConst.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in forConst.Body.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case DeferNode defer:
|
||||
{
|
||||
foreach (var n in defer.Statement.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case BinaryExpressionNode bin:
|
||||
{
|
||||
foreach (var n in bin.Left.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in bin.Right.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case UnaryExpressionNode unary:
|
||||
{
|
||||
foreach (var n in unary.Operand.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case FuncCallNode call:
|
||||
{
|
||||
foreach (var n in call.Expression.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in call.Parameters.SelectMany(param => param.EnumerateDescendantsAndSelf()))
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ArrayInitializerNode arrInit:
|
||||
{
|
||||
foreach (var n in arrInit.Values.SelectMany(val => val.EnumerateDescendantsAndSelf()))
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConstArrayInitializerNode constArrInit:
|
||||
{
|
||||
foreach (var n in constArrInit.Values.SelectMany(val => val.EnumerateDescendantsAndSelf()))
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ArrayIndexAccessNode arrIndex:
|
||||
{
|
||||
foreach (var n in arrIndex.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in arrIndex.Index.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConstArrayIndexAccessNode constArrIndex:
|
||||
{
|
||||
foreach (var n in constArrIndex.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in constArrIndex.Index.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case SliceIndexAccessNode sliceIndex:
|
||||
{
|
||||
foreach (var n in sliceIndex.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
foreach (var n in sliceIndex.Index.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case AddressOfNode addr:
|
||||
{
|
||||
foreach (var n in addr.LValue.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case StructFieldAccessNode field:
|
||||
{
|
||||
foreach (var n in field.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case StructInitializerNode structInit:
|
||||
{
|
||||
foreach (var n in structInit.Initializers.SelectMany(kv => kv.Value.EnumerateDescendantsAndSelf()))
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case DereferenceNode deref:
|
||||
{
|
||||
foreach (var n in deref.Target.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConvertIntNode convInt:
|
||||
{
|
||||
foreach (var n in convInt.Value.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConvertFloatNode convFloat:
|
||||
{
|
||||
foreach (var n in convFloat.Value.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConvertCStringToStringNode convStr:
|
||||
{
|
||||
foreach (var n in convStr.Value.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case FloatToIntBuiltinNode ftoi:
|
||||
{
|
||||
foreach (var n in ftoi.Value.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case ConstArrayToSliceNode constSlice:
|
||||
{
|
||||
foreach (var n in constSlice.Array.EnumerateDescendantsAndSelf())
|
||||
{
|
||||
yield return n;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
using NubLang.Ast;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
internal class CompletionHandler(WorkspaceManager workspaceManager) : CompletionHandlerBase
|
||||
{
|
||||
private readonly CompletionItem[] _definitionSnippets =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "func",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "func ${1:name}(${2:params})\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "struct",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "struct ${1:name}\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "module",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "module \"$0\"",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "import",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "import \"$0\"",
|
||||
}
|
||||
];
|
||||
|
||||
private readonly CompletionItem[] _statementSnippets =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "let",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "let ${1:name} = $0",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "if",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "if ${1:condition}\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "else if",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "else if ${1:condition}\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "else",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "else\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "while",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "while ${1:condition}\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "for",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "for ${1:name}, ${2:index} in ${3:array}\n{\n $0\n}",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "return",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "return $0",
|
||||
},
|
||||
new()
|
||||
{
|
||||
Kind = CompletionItemKind.Keyword,
|
||||
Label = "defer",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = "defer $0",
|
||||
}
|
||||
];
|
||||
|
||||
protected override CompletionRegistrationOptions CreateRegistrationOptions(CompletionCapability capability, ClientCapabilities clientCapabilities)
|
||||
{
|
||||
return new CompletionRegistrationOptions();
|
||||
}
|
||||
|
||||
public override Task<CompletionList> Handle(CompletionParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(HandleSync(request, cancellationToken));
|
||||
}
|
||||
|
||||
private CompletionList HandleSync(CompletionParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
var completions = new List<CompletionItem>();
|
||||
var position = request.Position;
|
||||
|
||||
var uri = request.TextDocument.Uri;
|
||||
var compilationUnit = workspaceManager.GetCompilationUnit(uri);
|
||||
if (compilationUnit != null)
|
||||
{
|
||||
var function = compilationUnit.Functions.FirstOrDefault(x => x.Body != null && x.Body.ContainsPosition(position.Line, position.Character));
|
||||
if (function != null)
|
||||
{
|
||||
completions.AddRange(_statementSnippets);
|
||||
|
||||
foreach (var prototype in compilationUnit.ImportedFunctions)
|
||||
{
|
||||
var parameterStrings = new List<string>();
|
||||
foreach (var (index, parameter) in prototype.Parameters.Index())
|
||||
{
|
||||
parameterStrings.AddRange($"${{{index + 1}:{parameter.Name}}}");
|
||||
}
|
||||
|
||||
completions.Add(new CompletionItem
|
||||
{
|
||||
Kind = CompletionItemKind.Function,
|
||||
Label = $"{prototype.Module}::{prototype.Name}",
|
||||
InsertTextFormat = InsertTextFormat.Snippet,
|
||||
InsertText = $"{prototype.Module}::{prototype.Name}({string.Join(", ", parameterStrings)})",
|
||||
});
|
||||
}
|
||||
|
||||
foreach (var parameter in function.Prototype.Parameters)
|
||||
{
|
||||
completions.Add(new CompletionItem
|
||||
{
|
||||
Kind = CompletionItemKind.Variable,
|
||||
Label = parameter.Name,
|
||||
InsertText = parameter.Name,
|
||||
});
|
||||
}
|
||||
|
||||
var variables = function
|
||||
.Body!
|
||||
.EnumerateDescendantsAndSelf()
|
||||
.OfType<VariableDeclarationNode>();
|
||||
|
||||
foreach (var variable in variables)
|
||||
{
|
||||
completions.Add(new CompletionItem
|
||||
{
|
||||
Kind = CompletionItemKind.Variable,
|
||||
Label = variable.Name,
|
||||
InsertText = variable.Name,
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
completions.AddRange(_definitionSnippets);
|
||||
}
|
||||
}
|
||||
|
||||
return new CompletionList(completions, false);
|
||||
}
|
||||
|
||||
public override Task<CompletionItem> Handle(CompletionItem request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new CompletionItem());
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
using NubLang.Ast;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
internal class DefinitionHandler(WorkspaceManager workspaceManager) : DefinitionHandlerBase
|
||||
{
|
||||
protected override DefinitionRegistrationOptions CreateRegistrationOptions(DefinitionCapability capability, ClientCapabilities clientCapabilities)
|
||||
{
|
||||
return new DefinitionRegistrationOptions();
|
||||
}
|
||||
|
||||
public override Task<LocationOrLocationLinks?> Handle(DefinitionParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(HandleSync(request, cancellationToken));
|
||||
}
|
||||
|
||||
private LocationOrLocationLinks? HandleSync(DefinitionParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
var uri = request.TextDocument.Uri;
|
||||
var compilationUnit = workspaceManager.GetCompilationUnit(uri);
|
||||
if (compilationUnit == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var line = request.Position.Line;
|
||||
var character = request.Position.Character;
|
||||
|
||||
var node = compilationUnit.DeepestNodeAtPosition(line, character);
|
||||
|
||||
switch (node)
|
||||
{
|
||||
case VariableIdentifierNode variableIdentifierNode:
|
||||
{
|
||||
var function = compilationUnit.FunctionAtPosition(line, character);
|
||||
|
||||
var parameter = function?.Prototype.Parameters.FirstOrDefault(x => x.Name == variableIdentifierNode.Name);
|
||||
if (parameter != null)
|
||||
{
|
||||
return new LocationOrLocationLinks(parameter.ToLocation());
|
||||
}
|
||||
|
||||
var variable = function?.Body?
|
||||
.EnumerateDescendantsAndSelf()
|
||||
.OfType<VariableDeclarationNode>()
|
||||
.FirstOrDefault(x => x.Name == variableIdentifierNode.Name);
|
||||
|
||||
if (variable != null)
|
||||
{
|
||||
return new LocationOrLocationLinks(variable.ToLocation());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
case FuncIdentifierNode funcIdentifierNode:
|
||||
{
|
||||
var prototype = compilationUnit.ImportedFunctions.FirstOrDefault(x => x.Module == funcIdentifierNode.Module && x.Name == funcIdentifierNode.Name);
|
||||
if (prototype != null)
|
||||
{
|
||||
return new LocationOrLocationLinks(prototype.ToLocation());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
|
||||
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
public class DiagnosticsPublisher
|
||||
{
|
||||
private readonly ILanguageServerFacade _server;
|
||||
|
||||
public DiagnosticsPublisher(ILanguageServerFacade server)
|
||||
{
|
||||
_server = server;
|
||||
}
|
||||
|
||||
public void Publish(DocumentUri uri, IEnumerable<Diagnostics.Diagnostic> diagnostics)
|
||||
{
|
||||
_server.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams
|
||||
{
|
||||
Uri = uri,
|
||||
Diagnostics = new Container<Diagnostic>(diagnostics.Select(MapDiagnostic))
|
||||
});
|
||||
}
|
||||
|
||||
private static Diagnostic MapDiagnostic(Diagnostics.Diagnostic nubDiagnostic)
|
||||
{
|
||||
return new Diagnostic
|
||||
{
|
||||
Severity = nubDiagnostic.Severity switch
|
||||
{
|
||||
Diagnostics.DiagnosticSeverity.Info => DiagnosticSeverity.Information,
|
||||
Diagnostics.DiagnosticSeverity.Warning => DiagnosticSeverity.Warning,
|
||||
Diagnostics.DiagnosticSeverity.Error => DiagnosticSeverity.Error,
|
||||
_ => null
|
||||
},
|
||||
Message = $"{nubDiagnostic.Message}\n{(nubDiagnostic.Help == null ? "" : $"help: {nubDiagnostic.Help}")}",
|
||||
Range = nubDiagnostic.Span.HasValue
|
||||
? new Range(nubDiagnostic.Span.Value.Start.Line - 1, nubDiagnostic.Span.Value.Start.Column - 1, nubDiagnostic.Span.Value.End.Line - 1, nubDiagnostic.Span.Value.End.Column - 1)
|
||||
: new Range(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
using System.Globalization;
|
||||
using NubLang.Ast;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
internal class HoverHandler(WorkspaceManager workspaceManager) : HoverHandlerBase
|
||||
{
|
||||
protected override HoverRegistrationOptions CreateRegistrationOptions(HoverCapability capability, ClientCapabilities clientCapabilities)
|
||||
{
|
||||
return new HoverRegistrationOptions
|
||||
{
|
||||
DocumentSelector = TextDocumentSelector.ForLanguage("nub")
|
||||
};
|
||||
}
|
||||
|
||||
public override Task<Hover?> Handle(HoverParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(HandleSync(request, cancellationToken));
|
||||
}
|
||||
|
||||
private Hover? HandleSync(HoverParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
var compilationUnit = workspaceManager.GetCompilationUnit(request.TextDocument.Uri);
|
||||
if (compilationUnit == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var line = request.Position.Line;
|
||||
var character = request.Position.Character;
|
||||
|
||||
var hoveredNode = compilationUnit.DeepestNodeAtPosition(line, character);
|
||||
|
||||
if (hoveredNode == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var message = CreateMessage(hoveredNode, compilationUnit);
|
||||
if (message == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Hover
|
||||
{
|
||||
Contents = new MarkedStringsOrMarkupContent(new MarkupContent
|
||||
{
|
||||
Value = message,
|
||||
Kind = MarkupKind.Markdown,
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
private static string? CreateMessage(Node hoveredNode, CompilationUnit compilationUnit)
|
||||
{
|
||||
return hoveredNode switch
|
||||
{
|
||||
FuncNode funcNode => CreateFuncPrototypeMessage(funcNode.Prototype),
|
||||
FuncPrototypeNode funcPrototypeNode => CreateFuncPrototypeMessage(funcPrototypeNode),
|
||||
FuncIdentifierNode funcIdentifierNode => CreateFuncIdentifierMessage(funcIdentifierNode, compilationUnit),
|
||||
FuncParameterNode funcParameterNode => CreateTypeNameMessage("Function parameter", funcParameterNode.Name, funcParameterNode.Type),
|
||||
VariableIdentifierNode variableIdentifierNode => CreateTypeNameMessage("Variable", variableIdentifierNode.Name, variableIdentifierNode.Type),
|
||||
VariableDeclarationNode variableDeclarationNode => CreateTypeNameMessage("Variable declaration", variableDeclarationNode.Name, variableDeclarationNode.Type),
|
||||
StructFieldAccessNode structFieldAccessNode => CreateTypeNameMessage("Struct field", $"{structFieldAccessNode.Target.Type}.{structFieldAccessNode.Field}", structFieldAccessNode.Type),
|
||||
CStringLiteralNode cStringLiteralNode => CreateLiteralMessage(cStringLiteralNode.Type, '"' + cStringLiteralNode.Value + '"'),
|
||||
StringLiteralNode stringLiteralNode => CreateLiteralMessage(stringLiteralNode.Type, '"' + stringLiteralNode.Value + '"'),
|
||||
BoolLiteralNode boolLiteralNode => CreateLiteralMessage(boolLiteralNode.Type, boolLiteralNode.Value.ToString()),
|
||||
Float32LiteralNode float32LiteralNode => CreateLiteralMessage(float32LiteralNode.Type, float32LiteralNode.Value.ToString(CultureInfo.InvariantCulture)),
|
||||
Float64LiteralNode float64LiteralNode => CreateLiteralMessage(float64LiteralNode.Type, float64LiteralNode.Value.ToString(CultureInfo.InvariantCulture)),
|
||||
I8LiteralNode i8LiteralNode => CreateLiteralMessage(i8LiteralNode.Type, i8LiteralNode.Value.ToString()),
|
||||
I16LiteralNode i16LiteralNode => CreateLiteralMessage(i16LiteralNode.Type, i16LiteralNode.Value.ToString()),
|
||||
I32LiteralNode i32LiteralNode => CreateLiteralMessage(i32LiteralNode.Type, i32LiteralNode.Value.ToString()),
|
||||
I64LiteralNode i64LiteralNode => CreateLiteralMessage(i64LiteralNode.Type, i64LiteralNode.Value.ToString()),
|
||||
U8LiteralNode u8LiteralNode => CreateLiteralMessage(u8LiteralNode.Type, u8LiteralNode.Value.ToString()),
|
||||
U16LiteralNode u16LiteralNode => CreateLiteralMessage(u16LiteralNode.Type, u16LiteralNode.Value.ToString()),
|
||||
U32LiteralNode u32LiteralNode => CreateLiteralMessage(u32LiteralNode.Type, u32LiteralNode.Value.ToString()),
|
||||
U64LiteralNode u64LiteralNode => CreateLiteralMessage(u64LiteralNode.Type, u64LiteralNode.Value.ToString()),
|
||||
// Expressions can have a generic fallback showing the resulting type
|
||||
ExpressionNode expressionNode => $"""
|
||||
**Expression** `{expressionNode.GetType().Name}`
|
||||
```nub
|
||||
{expressionNode.Type}
|
||||
```
|
||||
""",
|
||||
BlockNode => null,
|
||||
_ => hoveredNode.GetType().Name
|
||||
};
|
||||
}
|
||||
|
||||
private static string CreateLiteralMessage(NubType type, string value)
|
||||
{
|
||||
return $"""
|
||||
**Literal** `{type}`
|
||||
```nub
|
||||
{value}: {type}
|
||||
```
|
||||
""";
|
||||
}
|
||||
|
||||
private static string CreateTypeNameMessage(string description, string name, NubType type)
|
||||
{
|
||||
return $"""
|
||||
**{description}** `{name}`
|
||||
```nub
|
||||
{name}: {type}
|
||||
```
|
||||
""";
|
||||
}
|
||||
|
||||
private static string CreateFuncIdentifierMessage(FuncIdentifierNode funcIdentifierNode, CompilationUnit compilationUnit)
|
||||
{
|
||||
var func = compilationUnit.ImportedFunctions.FirstOrDefault(x => x.Module == funcIdentifierNode.Module && x.Name == funcIdentifierNode.Name);
|
||||
if (func == null)
|
||||
{
|
||||
return $"""
|
||||
**Function** `{funcIdentifierNode.Module}::{funcIdentifierNode.Name}`
|
||||
```nub
|
||||
// Declaration not found
|
||||
```
|
||||
""";
|
||||
}
|
||||
|
||||
return CreateFuncPrototypeMessage(func);
|
||||
}
|
||||
|
||||
private static string CreateFuncPrototypeMessage(FuncPrototypeNode funcPrototypeNode)
|
||||
{
|
||||
var parameterText = string.Join(", ", funcPrototypeNode.Parameters.Select(x => $"{x.Name}: {x.Type}"));
|
||||
var externText = funcPrototypeNode.ExternSymbol != null ? $"extern \"{funcPrototypeNode.ExternSymbol}\" " : "";
|
||||
|
||||
return $"""
|
||||
**Function** `{funcPrototypeNode.Module}::{funcPrototypeNode.Name}`
|
||||
```nub
|
||||
{externText}func {funcPrototypeNode.Module}::{funcPrototypeNode.Name}({parameterText}): {funcPrototypeNode.ReturnType}
|
||||
```
|
||||
""";
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>nublsp</AssemblyName>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="OmniSharp.Extensions.LanguageServer" Version="0.19.9" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\NubLang\NubLang.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,34 +0,0 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NubLang.LSP;
|
||||
using OmniSharp.Extensions.LanguageServer.Server;
|
||||
|
||||
var server = await LanguageServer.From(options => options
|
||||
.WithInput(Console.OpenStandardInput())
|
||||
.WithOutput(Console.OpenStandardOutput())
|
||||
.WithServices(services =>
|
||||
{
|
||||
services.AddSingleton<DiagnosticsPublisher>();
|
||||
services.AddSingleton<WorkspaceManager>();
|
||||
})
|
||||
.ConfigureLogging(x => x
|
||||
.AddLanguageProtocolLogging()
|
||||
.SetMinimumLevel(LogLevel.Debug))
|
||||
.WithHandler<TextDocumentSyncHandler>()
|
||||
.WithHandler<HoverHandler>()
|
||||
.WithHandler<CompletionHandler>()
|
||||
.WithHandler<DefinitionHandler>()
|
||||
.OnInitialize((server, request, ct) =>
|
||||
{
|
||||
var workspaceManager = server.GetRequiredService<WorkspaceManager>();
|
||||
|
||||
if (request.RootPath != null)
|
||||
{
|
||||
workspaceManager.Init(request.RootPath);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
})
|
||||
);
|
||||
|
||||
await server.WaitForExit;
|
||||
@@ -1,44 +0,0 @@
|
||||
using MediatR;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
internal class TextDocumentSyncHandler(WorkspaceManager workspaceManager) : TextDocumentSyncHandlerBase
|
||||
{
|
||||
public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri)
|
||||
{
|
||||
return new TextDocumentAttributes(uri, "nub");
|
||||
}
|
||||
|
||||
public override Task<Unit> Handle(DidOpenTextDocumentParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath());
|
||||
return Unit.Task;
|
||||
}
|
||||
|
||||
public override Task<Unit> Handle(DidChangeTextDocumentParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath());
|
||||
return Unit.Task;
|
||||
}
|
||||
|
||||
public override Task<Unit> Handle(DidSaveTextDocumentParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath());
|
||||
return Unit.Task;
|
||||
}
|
||||
|
||||
public override Task<Unit> Handle(DidCloseTextDocumentParams request, CancellationToken cancellationToken)
|
||||
{
|
||||
workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath());
|
||||
return Unit.Task;
|
||||
}
|
||||
|
||||
protected override TextDocumentSyncRegistrationOptions CreateRegistrationOptions(TextSynchronizationCapability capability, ClientCapabilities clientCapabilities)
|
||||
{
|
||||
return new TextDocumentSyncRegistrationOptions();
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
using NubLang.Ast;
|
||||
using NubLang.Generation;
|
||||
using NubLang.Syntax;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol;
|
||||
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
|
||||
|
||||
namespace NubLang.LSP;
|
||||
|
||||
public class WorkspaceManager(DiagnosticsPublisher diagnosticsPublisher, ILanguageServerFacade server)
|
||||
{
|
||||
private readonly Dictionary<string, SyntaxTree> _syntaxTrees = new();
|
||||
private readonly Dictionary<string, CompilationUnit> _compilationUnits = new();
|
||||
|
||||
public void Init(string rootPath)
|
||||
{
|
||||
var files = Directory.GetFiles(rootPath, "*.nub", SearchOption.AllDirectories);
|
||||
foreach (var path in files)
|
||||
{
|
||||
var text = File.ReadAllText(path);
|
||||
var tokenizer = new Tokenizer(path, text);
|
||||
|
||||
tokenizer.Tokenize();
|
||||
diagnosticsPublisher.Publish(path, tokenizer.Diagnostics);
|
||||
|
||||
var parser = new Parser();
|
||||
var parseResult = parser.Parse(tokenizer.Tokens);
|
||||
diagnosticsPublisher.Publish(path, parser.Diagnostics);
|
||||
|
||||
_syntaxTrees[path] = parseResult;
|
||||
}
|
||||
|
||||
Generate();
|
||||
}
|
||||
|
||||
public void UpdateFile(DocumentUri path)
|
||||
{
|
||||
var fsPath = path.GetFileSystemPath();
|
||||
var text = File.ReadAllText(fsPath);
|
||||
var tokenizer = new Tokenizer(fsPath, text);
|
||||
|
||||
tokenizer.Tokenize();
|
||||
diagnosticsPublisher.Publish(path, tokenizer.Diagnostics);
|
||||
|
||||
var parser = new Parser();
|
||||
var parseResult = parser.Parse(tokenizer.Tokens);
|
||||
diagnosticsPublisher.Publish(path, parser.Diagnostics);
|
||||
|
||||
_syntaxTrees[fsPath] = parseResult;
|
||||
|
||||
Generate();
|
||||
}
|
||||
|
||||
private void Generate()
|
||||
{
|
||||
var modules = Module.Collect(_syntaxTrees.Select(x => x.Value).ToList());
|
||||
|
||||
foreach (var (documentUri, syntaxTree) in _syntaxTrees)
|
||||
{
|
||||
var typeChecker = new TypeChecker(syntaxTree, modules);
|
||||
var result = typeChecker.Check();
|
||||
diagnosticsPublisher.Publish(documentUri, typeChecker.Diagnostics);
|
||||
_compilationUnits[documentUri] = result;
|
||||
|
||||
var generator = new Generator(result);
|
||||
var c = generator.Emit();
|
||||
|
||||
server.SendNotification("nub/output", new
|
||||
{
|
||||
content = c,
|
||||
uri = documentUri
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveFile(DocumentUri path)
|
||||
{
|
||||
var fsPath = path.GetFileSystemPath();
|
||||
_syntaxTrees.Remove(fsPath);
|
||||
_compilationUnits.Remove(fsPath);
|
||||
}
|
||||
|
||||
public Dictionary<string, CompilationUnit> GetCompilationUnits()
|
||||
{
|
||||
return _compilationUnits;
|
||||
}
|
||||
|
||||
public CompilationUnit? GetCompilationUnit(DocumentUri path)
|
||||
{
|
||||
return _compilationUnits.GetValueOrDefault(path.GetFileSystemPath());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
namespace NubLang.Ast;
|
||||
|
||||
public sealed class CompilationUnit
|
||||
{
|
||||
public CompilationUnit(List<FuncNode> functions, List<NubStructType> importedStructTypes, List<FuncPrototypeNode> importedFunctions)
|
||||
{
|
||||
Functions = functions;
|
||||
ImportedStructTypes = importedStructTypes;
|
||||
ImportedFunctions = importedFunctions;
|
||||
}
|
||||
|
||||
public List<FuncNode> Functions { get; }
|
||||
public List<NubStructType> ImportedStructTypes { get; }
|
||||
public List<FuncPrototypeNode> ImportedFunctions { get; }
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
using NubLang.Syntax;
|
||||
|
||||
namespace NubLang.Ast;
|
||||
|
||||
public abstract record Node(List<Token> Tokens);
|
||||
|
||||
#region Definitions
|
||||
|
||||
public abstract record DefinitionNode(List<Token> Tokens, string Module, string Name) : Node(Tokens);
|
||||
|
||||
public record FuncParameterNode(List<Token> Tokens, string Name, NubType Type) : Node(Tokens);
|
||||
|
||||
public record FuncPrototypeNode(List<Token> Tokens, string Module, string Name, string? ExternSymbol, List<FuncParameterNode> Parameters, NubType ReturnType) : Node(Tokens);
|
||||
|
||||
public record FuncNode(List<Token> Tokens, FuncPrototypeNode Prototype, BlockNode? Body) : DefinitionNode(Tokens, Prototype.Module, Prototype.Name);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Statements
|
||||
|
||||
public abstract record StatementNode(List<Token> Tokens) : Node(Tokens);
|
||||
|
||||
public abstract record TerminalStatementNode(List<Token> Tokens) : StatementNode(Tokens);
|
||||
|
||||
public record BlockNode(List<Token> Tokens, List<StatementNode> Statements) : StatementNode(Tokens);
|
||||
|
||||
public record StatementFuncCallNode(List<Token> Tokens, FuncCallNode FuncCall) : StatementNode(Tokens);
|
||||
|
||||
public record ReturnNode(List<Token> Tokens, ExpressionNode? Value) : TerminalStatementNode(Tokens);
|
||||
|
||||
public record AssignmentNode(List<Token> Tokens, LValueExpressionNode Target, ExpressionNode Value) : StatementNode(Tokens);
|
||||
|
||||
public record IfNode(List<Token> Tokens, ExpressionNode Condition, BlockNode Body, Variant<IfNode, BlockNode>? Else) : StatementNode(Tokens);
|
||||
|
||||
public record VariableDeclarationNode(List<Token> Tokens, string Name, ExpressionNode? Assignment, NubType Type) : StatementNode(Tokens);
|
||||
|
||||
public record ContinueNode(List<Token> Tokens) : TerminalStatementNode(Tokens);
|
||||
|
||||
public record BreakNode(List<Token> Tokens) : TerminalStatementNode(Tokens);
|
||||
|
||||
public record WhileNode(List<Token> Tokens, ExpressionNode Condition, BlockNode Body) : StatementNode(Tokens);
|
||||
|
||||
public record ForSliceNode(List<Token> Tokens, string ElementName, string? IndexName, ExpressionNode Target, BlockNode Body) : StatementNode(Tokens);
|
||||
|
||||
public record ForConstArrayNode(List<Token> Tokens, string ElementName, string? IndexName, ExpressionNode Target, BlockNode Body) : StatementNode(Tokens);
|
||||
|
||||
public record DeferNode(List<Token> Tokens, StatementNode Statement) : StatementNode(Tokens);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Expressions
|
||||
|
||||
public enum UnaryOperator
|
||||
{
|
||||
Negate,
|
||||
Invert
|
||||
}
|
||||
|
||||
public enum BinaryOperator
|
||||
{
|
||||
Equal,
|
||||
NotEqual,
|
||||
GreaterThan,
|
||||
GreaterThanOrEqual,
|
||||
LessThan,
|
||||
LessThanOrEqual,
|
||||
LogicalAnd,
|
||||
LogicalOr,
|
||||
Plus,
|
||||
Minus,
|
||||
Multiply,
|
||||
Divide,
|
||||
Modulo,
|
||||
LeftShift,
|
||||
RightShift,
|
||||
BitwiseAnd,
|
||||
BitwiseXor,
|
||||
BitwiseOr
|
||||
}
|
||||
|
||||
public abstract record ExpressionNode(List<Token> Tokens, NubType Type) : Node(Tokens);
|
||||
|
||||
public abstract record LValueExpressionNode(List<Token> Tokens, NubType Type) : ExpressionNode(Tokens, Type);
|
||||
|
||||
public abstract record RValueExpressionNode(List<Token> Tokens, NubType Type) : ExpressionNode(Tokens, Type);
|
||||
|
||||
public abstract record IntermediateExpression(List<Token> Tokens) : ExpressionNode(Tokens, new NubVoidType());
|
||||
|
||||
public record StringLiteralNode(List<Token> Tokens, string Value) : RValueExpressionNode(Tokens, new NubStringType());
|
||||
|
||||
public record CStringLiteralNode(List<Token> Tokens, string Value) : RValueExpressionNode(Tokens, new NubCStringType());
|
||||
|
||||
public record I8LiteralNode(List<Token> Tokens, sbyte Value) : RValueExpressionNode(Tokens, new NubIntType(true, 8));
|
||||
|
||||
public record I16LiteralNode(List<Token> Tokens, short Value) : RValueExpressionNode(Tokens, new NubIntType(true, 16));
|
||||
|
||||
public record I32LiteralNode(List<Token> Tokens, int Value) : RValueExpressionNode(Tokens, new NubIntType(true, 32));
|
||||
|
||||
public record I64LiteralNode(List<Token> Tokens, long Value) : RValueExpressionNode(Tokens, new NubIntType(true, 64));
|
||||
|
||||
public record U8LiteralNode(List<Token> Tokens, byte Value) : RValueExpressionNode(Tokens, new NubIntType(false, 8));
|
||||
|
||||
public record U16LiteralNode(List<Token> Tokens, ushort Value) : RValueExpressionNode(Tokens, new NubIntType(false, 16));
|
||||
|
||||
public record U32LiteralNode(List<Token> Tokens, uint Value) : RValueExpressionNode(Tokens, new NubIntType(false, 32));
|
||||
|
||||
public record U64LiteralNode(List<Token> Tokens, ulong Value) : RValueExpressionNode(Tokens, new NubIntType(false, 64));
|
||||
|
||||
public record Float32LiteralNode(List<Token> Tokens, float Value) : RValueExpressionNode(Tokens, new NubFloatType(32));
|
||||
|
||||
public record Float64LiteralNode(List<Token> Tokens, double Value) : RValueExpressionNode(Tokens, new NubFloatType(64));
|
||||
|
||||
public record BoolLiteralNode(List<Token> Tokens, NubType Type, bool Value) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record BinaryExpressionNode(List<Token> Tokens, NubType Type, ExpressionNode Left, BinaryOperator Operator, ExpressionNode Right) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record UnaryExpressionNode(List<Token> Tokens, NubType Type, UnaryOperator Operator, ExpressionNode Operand) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record FuncCallNode(List<Token> Tokens, NubType Type, ExpressionNode Expression, List<ExpressionNode> Parameters) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record VariableIdentifierNode(List<Token> Tokens, NubType Type, string Name) : LValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record FuncIdentifierNode(List<Token> Tokens, NubType Type, string Module, string Name, string? ExternSymbol) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record ArrayInitializerNode(List<Token> Tokens, NubType Type, List<ExpressionNode> Values) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record ConstArrayInitializerNode(List<Token> Tokens, NubType Type, List<ExpressionNode> Values) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record ArrayIndexAccessNode(List<Token> Tokens, NubType Type, ExpressionNode Target, ExpressionNode Index) : LValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record ConstArrayIndexAccessNode(List<Token> Tokens, NubType Type, ExpressionNode Target, ExpressionNode Index) : LValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record SliceIndexAccessNode(List<Token> Tokens, NubType Type, ExpressionNode Target, ExpressionNode Index) : LValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record AddressOfNode(List<Token> Tokens, NubType Type, LValueExpressionNode LValue) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record StructFieldAccessNode(List<Token> Tokens, NubType Type, ExpressionNode Target, string Field) : LValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record StructInitializerNode(List<Token> Tokens, NubType Type, Dictionary<string, ExpressionNode> Initializers) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record DereferenceNode(List<Token> Tokens, NubType Type, ExpressionNode Target) : LValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record ConvertIntNode(List<Token> Tokens, ExpressionNode Value, int StartWidth, int TargetWidth, bool StartSignedness, bool TargetSignedness) : RValueExpressionNode(Tokens, new NubIntType(TargetSignedness, TargetWidth));
|
||||
|
||||
public record ConvertFloatNode(List<Token> Tokens, ExpressionNode Value, int StartWidth, int TargetWidth) : RValueExpressionNode(Tokens, new NubFloatType(TargetWidth));
|
||||
|
||||
public record ConvertCStringToStringNode(List<Token> Tokens, ExpressionNode Value) : RValueExpressionNode(Tokens, new NubStringType());
|
||||
|
||||
public record SizeBuiltinNode(List<Token> Tokens, NubType Type, NubType TargetType) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record FloatToIntBuiltinNode(List<Token> Tokens, NubType Type, ExpressionNode Value, NubFloatType ValueType, NubIntType TargetType) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record ConstArrayToSliceNode(List<Token> Tokens, NubType Type, ExpressionNode Array) : RValueExpressionNode(Tokens, Type);
|
||||
|
||||
public record EnumReferenceIntermediateNode(List<Token> Tokens, string Module, string Name) : IntermediateExpression(Tokens);
|
||||
|
||||
#endregion
|
||||
@@ -1,171 +0,0 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace NubLang.Ast;
|
||||
|
||||
public abstract class NubType : IEquatable<NubType>
|
||||
{
|
||||
public override bool Equals(object? obj) => obj is NubType other && Equals(other);
|
||||
public abstract bool Equals(NubType? other);
|
||||
|
||||
public abstract override int GetHashCode();
|
||||
public abstract override string ToString();
|
||||
|
||||
public static bool operator ==(NubType? left, NubType? right) => Equals(left, right);
|
||||
public static bool operator !=(NubType? left, NubType? right) => !Equals(left, right);
|
||||
}
|
||||
|
||||
public class NubVoidType : NubType
|
||||
{
|
||||
public override string ToString() => "void";
|
||||
public override bool Equals(NubType? other) => other is NubVoidType;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubVoidType));
|
||||
}
|
||||
|
||||
public sealed class NubIntType(bool signed, int width) : NubType
|
||||
{
|
||||
public bool Signed { get; } = signed;
|
||||
public int Width { get; } = width;
|
||||
|
||||
public override string ToString() => $"{(Signed ? "i" : "u")}{Width}";
|
||||
public override bool Equals(NubType? other) => other is NubIntType @int && @int.Width == Width && @int.Signed == Signed;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubIntType), Signed, Width);
|
||||
}
|
||||
|
||||
public sealed class NubFloatType(int width) : NubType
|
||||
{
|
||||
public int Width { get; } = width;
|
||||
|
||||
public override string ToString() => $"f{Width}";
|
||||
public override bool Equals(NubType? other) => other is NubFloatType @float && @float.Width == Width;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubFloatType), Width);
|
||||
}
|
||||
|
||||
public class NubBoolType : NubType
|
||||
{
|
||||
public override string ToString() => "bool";
|
||||
public override bool Equals(NubType? other) => other is NubBoolType;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubBoolType));
|
||||
}
|
||||
|
||||
public sealed class NubPointerType(NubType baseType) : NubType
|
||||
{
|
||||
public NubType BaseType { get; } = baseType;
|
||||
|
||||
public override string ToString() => "^" + BaseType;
|
||||
public override bool Equals(NubType? other) => other is NubPointerType pointer && BaseType.Equals(pointer.BaseType);
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubPointerType), BaseType);
|
||||
}
|
||||
|
||||
public class NubFuncType(List<NubType> parameters, NubType returnType) : NubType
|
||||
{
|
||||
public List<NubType> Parameters { get; } = parameters;
|
||||
public NubType ReturnType { get; } = returnType;
|
||||
|
||||
public override string ToString() => $"func({string.Join(", ", Parameters)}): {ReturnType}";
|
||||
public override bool Equals(NubType? other) => other is NubFuncType func && ReturnType.Equals(func.ReturnType) && Parameters.SequenceEqual(func.Parameters);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = new HashCode();
|
||||
hash.Add(typeof(NubFuncType));
|
||||
hash.Add(ReturnType);
|
||||
foreach (var param in Parameters)
|
||||
{
|
||||
hash.Add(param);
|
||||
}
|
||||
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
public class NubStructType(string module, string name, List<NubStructFieldType> fields) : NubType
|
||||
{
|
||||
public string Module { get; } = module;
|
||||
public string Name { get; } = name;
|
||||
public List<NubStructFieldType> Fields { get; set; } = fields;
|
||||
|
||||
public override string ToString() => $"{Module}::{Name}";
|
||||
public override bool Equals(NubType? other) => other is NubStructType structType && Name == structType.Name && Module == structType.Module;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubStructType), Module, Name);
|
||||
}
|
||||
|
||||
public class NubStructFieldType(string name, NubType type, bool hasDefaultValue)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType Type { get; } = type;
|
||||
public bool HasDefaultValue { get; } = hasDefaultValue;
|
||||
}
|
||||
|
||||
public class NubSliceType(NubType elementType) : NubType
|
||||
{
|
||||
public NubType ElementType { get; } = elementType;
|
||||
|
||||
public override string ToString() => "[]" + ElementType;
|
||||
public override bool Equals(NubType? other) => other is NubSliceType slice && ElementType.Equals(slice.ElementType);
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubSliceType), ElementType);
|
||||
}
|
||||
|
||||
public class NubConstArrayType(NubType elementType, long size) : NubType
|
||||
{
|
||||
public NubType ElementType { get; } = elementType;
|
||||
public long Size { get; } = size;
|
||||
|
||||
public override string ToString() => $"[{Size}]{ElementType}";
|
||||
public override bool Equals(NubType? other) => other is NubConstArrayType array && ElementType.Equals(array.ElementType) && Size == array.Size;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubConstArrayType), ElementType, Size);
|
||||
}
|
||||
|
||||
public class NubArrayType(NubType elementType) : NubType
|
||||
{
|
||||
public NubType ElementType { get; } = elementType;
|
||||
|
||||
public override string ToString() => $"[?]{ElementType}";
|
||||
public override bool Equals(NubType? other) => other is NubArrayType array && ElementType.Equals(array.ElementType);
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubArrayType), ElementType);
|
||||
}
|
||||
|
||||
public class NubCStringType : NubType
|
||||
{
|
||||
public override string ToString() => "cstring";
|
||||
public override bool Equals(NubType? other) => other is NubCStringType;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubCStringType));
|
||||
}
|
||||
|
||||
public class NubStringType : NubType
|
||||
{
|
||||
public override string ToString() => "string";
|
||||
public override bool Equals(NubType? other) => other is NubStringType;
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(NubStringType));
|
||||
}
|
||||
|
||||
public static class NameMangler
|
||||
{
|
||||
public static string Mangle(params IEnumerable<NubType> types)
|
||||
{
|
||||
var readable = string.Join("_", types.Select(EncodeType));
|
||||
return ComputeShortHash(readable);
|
||||
}
|
||||
|
||||
private static string EncodeType(NubType node) => node switch
|
||||
{
|
||||
NubVoidType => "V",
|
||||
NubBoolType => "B",
|
||||
NubIntType i => (i.Signed ? "I" : "U") + i.Width,
|
||||
NubFloatType f => "F" + f.Width,
|
||||
NubCStringType => "CS",
|
||||
NubStringType => "S",
|
||||
NubPointerType p => "P" + EncodeType(p.BaseType),
|
||||
NubSliceType a => "A" + EncodeType(a.ElementType),
|
||||
NubFuncType fn => "FN(" + string.Join(",", fn.Parameters.Select(EncodeType)) + ")" + EncodeType(fn.ReturnType),
|
||||
NubStructType st => "ST(" + st.Module + "." + st.Name + ")",
|
||||
_ => throw new NotSupportedException($"Cannot encode type: {node}")
|
||||
};
|
||||
|
||||
private static string ComputeShortHash(string input)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(input);
|
||||
var hash = SHA256.HashData(bytes);
|
||||
return Convert.ToHexString(hash[..8]).ToLower();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,398 +0,0 @@
|
||||
using System.Text;
|
||||
using NubLang.Syntax;
|
||||
|
||||
namespace NubLang.Diagnostics;
|
||||
|
||||
public class Diagnostic
|
||||
{
|
||||
public class DiagnosticBuilder
|
||||
{
|
||||
private readonly DiagnosticSeverity _severity;
|
||||
private readonly string _message;
|
||||
private SourceSpan? _span;
|
||||
private string? _help;
|
||||
|
||||
public DiagnosticBuilder(DiagnosticSeverity severity, string message)
|
||||
{
|
||||
_severity = severity;
|
||||
_message = message;
|
||||
}
|
||||
|
||||
public DiagnosticBuilder At(SyntaxNode? node)
|
||||
{
|
||||
if (node != null)
|
||||
{
|
||||
_span = SourceSpan.Merge(node.Tokens.Select(x => x.Span));
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public DiagnosticBuilder At(Token? token)
|
||||
{
|
||||
if (token != null)
|
||||
{
|
||||
At(token.Span);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public DiagnosticBuilder At(SourceSpan? span)
|
||||
{
|
||||
if (span != null)
|
||||
{
|
||||
_span = span;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public DiagnosticBuilder At(string filePath, int line, int column)
|
||||
{
|
||||
_span = new SourceSpan(filePath, new SourceLocation(line, column), new SourceLocation(line, column));
|
||||
return this;
|
||||
}
|
||||
|
||||
public DiagnosticBuilder WithHelp(string help)
|
||||
{
|
||||
_help = help;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Diagnostic Build() => new(_severity, _message, _help, _span);
|
||||
}
|
||||
|
||||
public static DiagnosticBuilder Error(string message) => new(DiagnosticSeverity.Error, message);
|
||||
public static DiagnosticBuilder Warning(string message) => new(DiagnosticSeverity.Warning, message);
|
||||
public static DiagnosticBuilder Info(string message) => new(DiagnosticSeverity.Info, message);
|
||||
|
||||
public DiagnosticSeverity Severity { get; }
|
||||
public string Message { get; }
|
||||
public string? Help { get; }
|
||||
public SourceSpan? Span { get; }
|
||||
|
||||
private Diagnostic(DiagnosticSeverity severity, string message, string? help, SourceSpan? span)
|
||||
{
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Help = help;
|
||||
Span = span;
|
||||
}
|
||||
|
||||
public string FormatANSI()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
sb.Append(Severity switch
|
||||
{
|
||||
DiagnosticSeverity.Error => ConsoleColors.Colorize("error", ConsoleColors.Bold + ConsoleColors.Red),
|
||||
DiagnosticSeverity.Warning => ConsoleColors.Colorize("warning", ConsoleColors.Bold + ConsoleColors.Yellow),
|
||||
DiagnosticSeverity.Info => ConsoleColors.Colorize("info", ConsoleColors.Bold + ConsoleColors.Blue),
|
||||
_ => ConsoleColors.Colorize("unknown", ConsoleColors.Bold + ConsoleColors.White)
|
||||
});
|
||||
|
||||
if (Span.HasValue)
|
||||
{
|
||||
sb.Append(ConsoleColors.Colorize($" at {Span.Value}", ConsoleColors.Faint));
|
||||
}
|
||||
|
||||
sb.Append(": ");
|
||||
sb.Append(ConsoleColors.Colorize(Message, ConsoleColors.BrightWhite));
|
||||
|
||||
if (Span.HasValue)
|
||||
{
|
||||
sb.AppendLine();
|
||||
var text = File.ReadAllText(Span.Value.FilePath);
|
||||
|
||||
var tokenizer = new Tokenizer(Span.Value.FilePath, text);
|
||||
tokenizer.Tokenize();
|
||||
|
||||
var lines = text.Split('\n');
|
||||
|
||||
var startLine = Span.Value.Start.Line;
|
||||
var endLine = Span.Value.End.Line;
|
||||
|
||||
const int CONTEXT_LINES = 3;
|
||||
|
||||
var contextStartLine = Math.Max(1, startLine - CONTEXT_LINES);
|
||||
var contextEndLine = Math.Min(lines.Length, endLine + CONTEXT_LINES);
|
||||
|
||||
var numberPadding = contextEndLine.ToString().Length;
|
||||
|
||||
var codePadding = 0;
|
||||
for (var i = contextStartLine - 1; i < contextEndLine && i < lines.Length; i++)
|
||||
{
|
||||
var lineLength = lines[i].Length;
|
||||
if (lineLength > codePadding)
|
||||
{
|
||||
codePadding = lineLength;
|
||||
}
|
||||
}
|
||||
|
||||
sb.Append('╭');
|
||||
sb.Append(new string('─', numberPadding + 2));
|
||||
sb.Append('┬');
|
||||
sb.Append(new string('─', codePadding + 2));
|
||||
sb.Append('╮');
|
||||
sb.AppendLine();
|
||||
|
||||
for (var i = contextStartLine; i <= contextEndLine; i++)
|
||||
{
|
||||
var line = lines[i - 1];
|
||||
|
||||
sb.Append("│ ");
|
||||
sb.Append(i.ToString().PadRight(numberPadding));
|
||||
sb.Append(" │ ");
|
||||
sb.Append(ApplySyntaxHighlighting(line.PadRight(codePadding), i, tokenizer.Tokens));
|
||||
// sb.Append(line.PadRight(codePadding));
|
||||
sb.Append(" │");
|
||||
sb.AppendLine();
|
||||
|
||||
if (i >= startLine && i <= endLine)
|
||||
{
|
||||
var markerStartColumn = 1;
|
||||
var markerEndColumn = line.Length;
|
||||
|
||||
if (i == startLine)
|
||||
{
|
||||
markerStartColumn = Span.Value.Start.Column;
|
||||
}
|
||||
|
||||
if (i == endLine)
|
||||
{
|
||||
markerEndColumn = Span.Value.End.Column;
|
||||
}
|
||||
|
||||
var markerLength = markerEndColumn - markerStartColumn;
|
||||
var marker = new string('^', markerLength);
|
||||
|
||||
var markerColor = Severity switch
|
||||
{
|
||||
DiagnosticSeverity.Info => ConsoleColors.Blue,
|
||||
DiagnosticSeverity.Warning => ConsoleColors.Yellow,
|
||||
DiagnosticSeverity.Error => ConsoleColors.Red,
|
||||
_ => ConsoleColors.White
|
||||
};
|
||||
|
||||
sb.Append("│ ");
|
||||
sb.Append(new string(' ', numberPadding));
|
||||
sb.Append(" │ ");
|
||||
sb.Append(new string(' ', markerStartColumn - 1));
|
||||
sb.Append(ConsoleColors.Colorize(marker, markerColor));
|
||||
sb.Append(new string(' ', codePadding - (markerStartColumn - 1) - markerLength));
|
||||
sb.Append(" │");
|
||||
sb.AppendLine();
|
||||
}
|
||||
}
|
||||
|
||||
sb.Append('╰');
|
||||
sb.Append(new string('─', numberPadding + 2));
|
||||
sb.Append('┴');
|
||||
sb.Append(new string('─', codePadding + 2));
|
||||
sb.Append('╯');
|
||||
}
|
||||
|
||||
if (Help != null)
|
||||
{
|
||||
sb.AppendLine();
|
||||
sb.Append(ConsoleColors.Colorize($"help: {Help}", ConsoleColors.Cyan));
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string ApplySyntaxHighlighting(string line, int lineNumber, List<Token> tokens)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
var lineTokens = tokens
|
||||
.Where(t => t.Span.Start.Line == lineNumber)
|
||||
.OrderBy(t => t.Span.Start.Column)
|
||||
.ToList();
|
||||
|
||||
if (lineTokens.Count == 0)
|
||||
{
|
||||
return line;
|
||||
}
|
||||
|
||||
var currentColumn = 1;
|
||||
|
||||
foreach (var token in lineTokens)
|
||||
{
|
||||
var tokenStart = token.Span.Start.Column;
|
||||
var tokenEnd = token.Span.End.Column;
|
||||
|
||||
if (tokenStart > currentColumn && currentColumn - 1 < line.Length)
|
||||
{
|
||||
var beforeLength = Math.Min(tokenStart - currentColumn, line.Length - (currentColumn - 1));
|
||||
if (beforeLength > 0)
|
||||
{
|
||||
var beforeToken = line.Substring(currentColumn - 1, beforeLength);
|
||||
sb.Append(beforeToken);
|
||||
}
|
||||
}
|
||||
|
||||
var tokenLength = tokenEnd - tokenStart;
|
||||
if (tokenStart >= 1 && tokenStart - 1 < line.Length && tokenLength > 0)
|
||||
{
|
||||
var availableLength = line.Length - (tokenStart - 1);
|
||||
var actualLength = Math.Min(tokenLength, availableLength);
|
||||
|
||||
if (actualLength > 0)
|
||||
{
|
||||
var tokenText = line.Substring(tokenStart - 1, actualLength);
|
||||
var coloredToken = ColorizeToken(token, tokenText);
|
||||
sb.Append(coloredToken);
|
||||
}
|
||||
}
|
||||
|
||||
currentColumn = tokenEnd;
|
||||
}
|
||||
|
||||
if (currentColumn - 1 < line.Length)
|
||||
{
|
||||
var remaining = line[(currentColumn - 1)..];
|
||||
sb.Append(remaining);
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string ColorizeToken(Token token, string tokenText)
|
||||
{
|
||||
switch (token)
|
||||
{
|
||||
case IdentifierToken:
|
||||
{
|
||||
return ConsoleColors.Colorize(tokenText, ConsoleColors.BrightWhite);
|
||||
}
|
||||
case StringLiteralToken:
|
||||
{
|
||||
return ConsoleColors.Colorize(tokenText, ConsoleColors.Green);
|
||||
}
|
||||
case IntLiteralToken:
|
||||
case FloatLiteralToken:
|
||||
case BoolLiteralToken:
|
||||
{
|
||||
return ConsoleColors.Colorize(tokenText, ConsoleColors.Magenta);
|
||||
}
|
||||
case SymbolToken symbolToken:
|
||||
{
|
||||
switch (symbolToken.Symbol)
|
||||
{
|
||||
case Symbol.Func:
|
||||
case Symbol.Return:
|
||||
case Symbol.If:
|
||||
case Symbol.Else:
|
||||
case Symbol.While:
|
||||
case Symbol.Break:
|
||||
case Symbol.Continue:
|
||||
case Symbol.Struct:
|
||||
case Symbol.Let:
|
||||
case Symbol.Extern:
|
||||
case Symbol.For:
|
||||
case Symbol.In:
|
||||
{
|
||||
return ConsoleColors.Colorize(tokenText, ConsoleColors.Bold + ConsoleColors.Blue);
|
||||
}
|
||||
case Symbol.Assign:
|
||||
case Symbol.Bang:
|
||||
case Symbol.Equal:
|
||||
case Symbol.NotEqual:
|
||||
case Symbol.LessThan:
|
||||
case Symbol.LessThanOrEqual:
|
||||
case Symbol.GreaterThan:
|
||||
case Symbol.GreaterThanOrEqual:
|
||||
case Symbol.Plus:
|
||||
case Symbol.Minus:
|
||||
case Symbol.Star:
|
||||
case Symbol.ForwardSlash:
|
||||
case Symbol.Caret:
|
||||
case Symbol.Ampersand:
|
||||
{
|
||||
return ConsoleColors.Colorize(tokenText, ConsoleColors.Yellow);
|
||||
}
|
||||
case Symbol.Colon:
|
||||
case Symbol.OpenParen:
|
||||
case Symbol.CloseParen:
|
||||
case Symbol.OpenBrace:
|
||||
case Symbol.CloseBrace:
|
||||
case Symbol.OpenBracket:
|
||||
case Symbol.CloseBracket:
|
||||
case Symbol.Comma:
|
||||
case Symbol.Period:
|
||||
case Symbol.Semi:
|
||||
{
|
||||
return ConsoleColors.Colorize(tokenText, ConsoleColors.BrightBlack);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return tokenText;
|
||||
}
|
||||
}
|
||||
|
||||
public enum DiagnosticSeverity
|
||||
{
|
||||
Info,
|
||||
Warning,
|
||||
Error
|
||||
}
|
||||
|
||||
public static class ConsoleColors
|
||||
{
|
||||
public const string Reset = "\e[0m";
|
||||
public const string Bold = "\e[1m";
|
||||
public const string Faint = "\e[2m";
|
||||
public const string Italic = "\e[3m";
|
||||
public const string Underline = "\e[4m";
|
||||
public const string SlowBlink = "\e[5m";
|
||||
public const string RapidBlink = "\e[6m";
|
||||
public const string SwapBgAndFg = "\e[7m";
|
||||
public const string Conceal = "\e[8m";
|
||||
public const string CrossedOut = "\e[9m";
|
||||
|
||||
public const string DefaultFont = "\e[10m";
|
||||
public const string AltFont1 = "\e[11m";
|
||||
public const string AltFont2 = "\e[12m";
|
||||
public const string AltFont3 = "\e[13m";
|
||||
public const string AltFont4 = "\e[14m";
|
||||
public const string AltFont5 = "\e[15m";
|
||||
public const string AltFont6 = "\e[16m";
|
||||
public const string AltFont7 = "\e[17m";
|
||||
public const string AltFont8 = "\e[18m";
|
||||
public const string AltFont9 = "\e[19m";
|
||||
|
||||
public const string Black = "\e[30m";
|
||||
public const string Red = "\e[31m";
|
||||
public const string Green = "\e[32m";
|
||||
public const string Yellow = "\e[33m";
|
||||
public const string Blue = "\e[34m";
|
||||
public const string Magenta = "\e[35m";
|
||||
public const string Cyan = "\e[36m";
|
||||
public const string White = "\e[37m";
|
||||
|
||||
public const string BrightBlack = "\e[90m";
|
||||
public const string BrightRed = "\e[91m";
|
||||
public const string BrightGreen = "\e[92m";
|
||||
public const string BrightYellow = "\e[93m";
|
||||
public const string BrightBlue = "\e[94m";
|
||||
public const string BrightMagenta = "\e[95m";
|
||||
public const string BrightCyan = "\e[96m";
|
||||
public const string BrightWhite = "\e[97m";
|
||||
|
||||
private static bool IsColorSupported()
|
||||
{
|
||||
var term = Environment.GetEnvironmentVariable("TERM");
|
||||
var colorTerm = Environment.GetEnvironmentVariable("COLORTERM");
|
||||
return !string.IsNullOrEmpty(term) || !string.IsNullOrEmpty(colorTerm) || !Console.IsOutputRedirected;
|
||||
}
|
||||
|
||||
public static string Colorize(string text, string color)
|
||||
{
|
||||
return IsColorSupported() ? $"{color}{text}{Reset}" : text;
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
namespace NubLang.Diagnostics;
|
||||
|
||||
public readonly struct SourceSpan : IEquatable<SourceSpan>, IComparable<SourceSpan>
|
||||
{
|
||||
public static SourceSpan Merge(params IEnumerable<SourceSpan> spans)
|
||||
{
|
||||
var spanArray = spans as SourceSpan[] ?? spans.ToArray();
|
||||
if (spanArray.Length == 0)
|
||||
{
|
||||
return new SourceSpan(string.Empty, new SourceLocation(0, 0), new SourceLocation(0, 0));
|
||||
}
|
||||
|
||||
var minStart = spanArray.Min(s => s.Start);
|
||||
var maxEnd = spanArray.Max(s => s.End);
|
||||
|
||||
return new SourceSpan(spanArray[0].FilePath, minStart, maxEnd);
|
||||
}
|
||||
|
||||
public SourceSpan(string filePath, SourceLocation start, SourceLocation end)
|
||||
{
|
||||
if (start > end)
|
||||
{
|
||||
throw new ArgumentException("Start location cannot be after end location");
|
||||
}
|
||||
|
||||
FilePath = filePath;
|
||||
Start = start;
|
||||
End = end;
|
||||
}
|
||||
|
||||
public string FilePath { get; }
|
||||
public SourceLocation Start { get; }
|
||||
public SourceLocation End { get; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
if (Start == End)
|
||||
{
|
||||
return $"{FilePath}:{Start}";
|
||||
}
|
||||
|
||||
if (Start.Line == End.Line)
|
||||
{
|
||||
return Start.Column == End.Column ? $"{FilePath}:{Start}" : $"{FilePath}:{Start.Line}:{Start.Column}-{End.Column}";
|
||||
}
|
||||
|
||||
return $"{FilePath}:{Start}-{End}";
|
||||
}
|
||||
|
||||
public bool Equals(SourceSpan other) => Start == other.Start && End == other.End;
|
||||
public override bool Equals(object? obj) => obj is SourceSpan other && Equals(other);
|
||||
public override int GetHashCode() => HashCode.Combine(typeof(SourceSpan), Start, End);
|
||||
|
||||
public static bool operator ==(SourceSpan left, SourceSpan right) => Equals(left, right);
|
||||
public static bool operator !=(SourceSpan left, SourceSpan right) => !Equals(left, right);
|
||||
|
||||
public static bool operator <(SourceSpan left, SourceSpan right) => left.CompareTo(right) < 0;
|
||||
public static bool operator <=(SourceSpan left, SourceSpan right) => left.CompareTo(right) <= 0;
|
||||
public static bool operator >(SourceSpan left, SourceSpan right) => left.CompareTo(right) > 0;
|
||||
public static bool operator >=(SourceSpan left, SourceSpan right) => left.CompareTo(right) >= 0;
|
||||
|
||||
public int CompareTo(SourceSpan other)
|
||||
{
|
||||
var startComparison = Start.CompareTo(other.Start);
|
||||
return startComparison != 0 ? startComparison : End.CompareTo(other.End);
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct SourceLocation : IEquatable<SourceLocation>, IComparable<SourceLocation>
|
||||
{
|
||||
public SourceLocation(int line, int column)
|
||||
{
|
||||
Line = line;
|
||||
Column = column;
|
||||
}
|
||||
|
||||
public int Line { get; }
|
||||
public int Column { get; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{Line}:{Column}";
|
||||
}
|
||||
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
return obj is SourceLocation other && Equals(other);
|
||||
}
|
||||
|
||||
public bool Equals(SourceLocation other)
|
||||
{
|
||||
return Line == other.Line && Column == other.Column;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return HashCode.Combine(typeof(SourceLocation), Line, Column);
|
||||
}
|
||||
|
||||
public static bool operator ==(SourceLocation left, SourceLocation right) => Equals(left, right);
|
||||
public static bool operator !=(SourceLocation left, SourceLocation right) => !Equals(left, right);
|
||||
public static bool operator <(SourceLocation left, SourceLocation right) => left.Line < right.Line || (left.Line == right.Line && left.Column < right.Column);
|
||||
public static bool operator >(SourceLocation left, SourceLocation right) => left.Line > right.Line || (left.Line == right.Line && left.Column > right.Column);
|
||||
public static bool operator <=(SourceLocation left, SourceLocation right) => left.Line <= right.Line || (left.Line == right.Line && left.Column <= right.Column);
|
||||
public static bool operator >=(SourceLocation left, SourceLocation right) => left.Line >= right.Line || (left.Line == right.Line && left.Column >= right.Column);
|
||||
|
||||
public int CompareTo(SourceLocation other)
|
||||
{
|
||||
var lineComparison = Line.CompareTo(other.Line);
|
||||
return lineComparison != 0 ? lineComparison : Column.CompareTo(other.Column);
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
using NubLang.Ast;
|
||||
|
||||
namespace NubLang.Generation;
|
||||
|
||||
public static class CType
|
||||
{
|
||||
public static string Create(NubType type, string? variableName = null, bool constArraysAsPointers = true)
|
||||
{
|
||||
return type switch
|
||||
{
|
||||
NubVoidType => "void" + (variableName != null ? $" {variableName}" : ""),
|
||||
NubBoolType => "bool" + (variableName != null ? $" {variableName}" : ""),
|
||||
NubIntType intType => CreateIntType(intType, variableName),
|
||||
NubFloatType floatType => CreateFloatType(floatType, variableName),
|
||||
NubCStringType => "char*" + (variableName != null ? $" {variableName}" : ""),
|
||||
NubPointerType ptr => CreatePointerType(ptr, variableName),
|
||||
NubSliceType => "slice" + (variableName != null ? $" {variableName}" : ""),
|
||||
NubStringType => "string" + (variableName != null ? $" {variableName}" : ""),
|
||||
NubConstArrayType arr => CreateConstArrayType(arr, variableName, constArraysAsPointers),
|
||||
NubArrayType arr => CreateArrayType(arr, variableName),
|
||||
NubFuncType fn => CreateFuncType(fn, variableName),
|
||||
NubStructType st => $"{st.Module}_{st.Name}" + (variableName != null ? $" {variableName}" : ""),
|
||||
_ => throw new NotSupportedException($"C type generation not supported for: {type}")
|
||||
};
|
||||
}
|
||||
|
||||
private static string CreateIntType(NubIntType intType, string? varName)
|
||||
{
|
||||
var cType = intType.Width switch
|
||||
{
|
||||
8 => intType.Signed ? "int8_t" : "uint8_t",
|
||||
16 => intType.Signed ? "int16_t" : "uint16_t",
|
||||
32 => intType.Signed ? "int32_t" : "uint32_t",
|
||||
64 => intType.Signed ? "int64_t" : "uint64_t",
|
||||
_ => throw new NotSupportedException($"Unsupported integer width: {intType.Width}")
|
||||
};
|
||||
return cType + (varName != null ? $" {varName}" : "");
|
||||
}
|
||||
|
||||
private static string CreateFloatType(NubFloatType floatType, string? varName)
|
||||
{
|
||||
var cType = floatType.Width switch
|
||||
{
|
||||
32 => "float",
|
||||
64 => "double",
|
||||
_ => throw new NotSupportedException($"Unsupported float width: {floatType.Width}")
|
||||
};
|
||||
return cType + (varName != null ? $" {varName}" : "");
|
||||
}
|
||||
|
||||
private static string CreatePointerType(NubPointerType ptr, string? varName)
|
||||
{
|
||||
var baseType = Create(ptr.BaseType);
|
||||
return baseType + "*" + (varName != null ? $" {varName}" : "");
|
||||
}
|
||||
|
||||
private static string CreateConstArrayType(NubConstArrayType arr, string? varName, bool inStructDef)
|
||||
{
|
||||
var elementType = Create(arr.ElementType);
|
||||
|
||||
// Treat const arrays as pointers unless in a struct definition
|
||||
if (!inStructDef)
|
||||
{
|
||||
return elementType + "*" + (varName != null ? $" {varName}" : "");
|
||||
}
|
||||
|
||||
if (varName != null)
|
||||
{
|
||||
return $"{elementType} {varName}[{arr.Size}]";
|
||||
}
|
||||
|
||||
return $"{elementType}[{arr.Size}]";
|
||||
}
|
||||
|
||||
private static string CreateArrayType(NubArrayType arr, string? varName)
|
||||
{
|
||||
var elementType = Create(arr.ElementType);
|
||||
return elementType + "*" + (varName != null ? $" {varName}" : "");
|
||||
}
|
||||
|
||||
private static string CreateFuncType(NubFuncType fn, string? varName)
|
||||
{
|
||||
var returnType = Create(fn.ReturnType);
|
||||
var parameters = string.Join(", ", fn.Parameters.Select(p => Create(p)));
|
||||
|
||||
if (string.IsNullOrEmpty(parameters))
|
||||
{
|
||||
parameters = "void";
|
||||
}
|
||||
|
||||
if (varName != null)
|
||||
{
|
||||
return $"{returnType} (*{varName})({parameters})";
|
||||
}
|
||||
|
||||
return $"{returnType} (*)({parameters})";
|
||||
}
|
||||
}
|
||||
@@ -1,644 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using NubLang.Ast;
|
||||
using NubLang.Syntax;
|
||||
|
||||
namespace NubLang.Generation;
|
||||
|
||||
public class Generator
|
||||
{
|
||||
private readonly CompilationUnit _compilationUnit;
|
||||
private readonly IndentedTextWriter _writer;
|
||||
private readonly Stack<List<DeferNode>> _deferStack = [];
|
||||
private int _tmpIndex;
|
||||
|
||||
public Generator(CompilationUnit compilationUnit)
|
||||
{
|
||||
_compilationUnit = compilationUnit;
|
||||
_writer = new IndentedTextWriter();
|
||||
}
|
||||
|
||||
// todo(nub31): Handle name collisions
|
||||
private string NewTmp()
|
||||
{
|
||||
return $"_t{++_tmpIndex}";
|
||||
}
|
||||
|
||||
private static string FuncName(string module, string name, string? externSymbol)
|
||||
{
|
||||
return externSymbol ?? $"{module}_{name}";
|
||||
}
|
||||
|
||||
private static string StructName(string module, string name)
|
||||
{
|
||||
return $"{module}_{name}";
|
||||
}
|
||||
|
||||
public string Emit()
|
||||
{
|
||||
_writer.WriteLine("""
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct
|
||||
{
|
||||
size_t length;
|
||||
char *data;
|
||||
} string;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
size_t length;
|
||||
void *data;
|
||||
} slice;
|
||||
|
||||
""");
|
||||
|
||||
foreach (var structType in _compilationUnit.ImportedStructTypes)
|
||||
{
|
||||
_writer.WriteLine("typedef struct");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
foreach (var field in structType.Fields)
|
||||
{
|
||||
_writer.WriteLine($"{CType.Create(field.Type, field.Name, constArraysAsPointers: false)};");
|
||||
}
|
||||
}
|
||||
|
||||
_writer.WriteLine($"}} {StructName(structType.Module, structType.Name)};");
|
||||
_writer.WriteLine();
|
||||
}
|
||||
|
||||
// note(nub31): Forward declarations
|
||||
foreach (var prototype in _compilationUnit.ImportedFunctions)
|
||||
{
|
||||
EmitLine(prototype.Tokens.FirstOrDefault());
|
||||
var parameters = prototype.Parameters.Count != 0
|
||||
? string.Join(", ", prototype.Parameters.Select(x => CType.Create(x.Type, x.Name)))
|
||||
: "void";
|
||||
|
||||
var name = FuncName(prototype.Module, prototype.Name, prototype.ExternSymbol);
|
||||
_writer.WriteLine($"{CType.Create(prototype.ReturnType, name)}({parameters});");
|
||||
_writer.WriteLine();
|
||||
}
|
||||
|
||||
// note(nub31): Normal functions
|
||||
foreach (var funcNode in _compilationUnit.Functions)
|
||||
{
|
||||
if (funcNode.Body == null) continue;
|
||||
|
||||
EmitLine(funcNode.Tokens.FirstOrDefault());
|
||||
var parameters = funcNode.Prototype.Parameters.Count != 0
|
||||
? string.Join(", ", funcNode.Prototype.Parameters.Select(x => CType.Create(x.Type, x.Name)))
|
||||
: "void";
|
||||
|
||||
var name = FuncName(funcNode.Module, funcNode.Name, funcNode.Prototype.ExternSymbol);
|
||||
_writer.WriteLine($"{CType.Create(funcNode.Prototype.ReturnType, name)}({parameters})");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
EmitBlock(funcNode.Body);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
_writer.WriteLine();
|
||||
}
|
||||
|
||||
return _writer.ToString();
|
||||
}
|
||||
|
||||
private void EmitStatement(StatementNode statementNode)
|
||||
{
|
||||
EmitLine(statementNode.Tokens.FirstOrDefault());
|
||||
switch (statementNode)
|
||||
{
|
||||
case AssignmentNode assignmentNode:
|
||||
EmitAssignment(assignmentNode);
|
||||
break;
|
||||
case BlockNode blockNode:
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
EmitBlock(blockNode);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
break;
|
||||
case BreakNode breakNode:
|
||||
EmitBreak(breakNode);
|
||||
break;
|
||||
case ContinueNode continueNode:
|
||||
EmitContinue(continueNode);
|
||||
break;
|
||||
case DeferNode deferNode:
|
||||
EmitDefer(deferNode);
|
||||
break;
|
||||
case ForConstArrayNode forConstArrayNode:
|
||||
EmitForConstArray(forConstArrayNode);
|
||||
break;
|
||||
case ForSliceNode forSliceNode:
|
||||
EmitForSlice(forSliceNode);
|
||||
break;
|
||||
case IfNode ifNode:
|
||||
EmitIf(ifNode);
|
||||
break;
|
||||
case ReturnNode returnNode:
|
||||
EmitReturn(returnNode);
|
||||
break;
|
||||
case StatementFuncCallNode statementFuncCallNode:
|
||||
EmitStatementFuncCall(statementFuncCallNode);
|
||||
break;
|
||||
case VariableDeclarationNode variableDeclarationNode:
|
||||
EmitVariableDeclaration(variableDeclarationNode);
|
||||
break;
|
||||
case WhileNode whileNode:
|
||||
EmitWhile(whileNode);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(statementNode));
|
||||
}
|
||||
}
|
||||
|
||||
private void EmitLine(Token? token)
|
||||
{
|
||||
if (token == null) return;
|
||||
var file = token.Span.FilePath;
|
||||
var line = token.Span.Start.Line;
|
||||
_writer.WriteLine($"#line {line} \"{file}\"");
|
||||
}
|
||||
|
||||
private void EmitAssignment(AssignmentNode assignmentNode)
|
||||
{
|
||||
var target = EmitExpression(assignmentNode.Target);
|
||||
var value = EmitExpression(assignmentNode.Value);
|
||||
_writer.WriteLine($"{target} = {value};");
|
||||
}
|
||||
|
||||
private void EmitBreak(BreakNode _)
|
||||
{
|
||||
// todo(nub31): Emit deferred statements
|
||||
_writer.WriteLine("break;");
|
||||
}
|
||||
|
||||
private void EmitContinue(ContinueNode _)
|
||||
{
|
||||
// todo(nub31): Emit deferred statements
|
||||
_writer.WriteLine("continue;");
|
||||
}
|
||||
|
||||
private void EmitDefer(DeferNode deferNode)
|
||||
{
|
||||
_deferStack.Peek().Add(deferNode);
|
||||
}
|
||||
|
||||
private void EmitForSlice(ForSliceNode forSliceNode)
|
||||
{
|
||||
var targetType = (NubSliceType)forSliceNode.Target.Type;
|
||||
var target = EmitExpression(forSliceNode.Target);
|
||||
var indexName = forSliceNode.IndexName ?? NewTmp();
|
||||
|
||||
_writer.WriteLine($"for (size_t {indexName} = 0; {indexName} < {target}.length; ++{indexName})");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
_writer.WriteLine($"{CType.Create(targetType.ElementType, forSliceNode.ElementName)} = (({CType.Create(targetType.ElementType)}*){target}.data)[{indexName}];");
|
||||
EmitBlock(forSliceNode.Body);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private void EmitForConstArray(ForConstArrayNode forConstArrayNode)
|
||||
{
|
||||
var targetType = (NubConstArrayType)forConstArrayNode.Target.Type;
|
||||
var target = EmitExpression(forConstArrayNode.Target);
|
||||
var indexName = forConstArrayNode.IndexName ?? NewTmp();
|
||||
|
||||
_writer.WriteLine($"for (size_t {indexName} = 0; {indexName} < {targetType.Size}; ++{indexName})");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
_writer.WriteLine($"{CType.Create(targetType.ElementType, forConstArrayNode.ElementName)} = {target}[{indexName}];");
|
||||
EmitBlock(forConstArrayNode.Body);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private void EmitIf(IfNode ifNode, bool elseIf = false)
|
||||
{
|
||||
var condition = EmitExpression(ifNode.Condition);
|
||||
_writer.WriteLine($"{(elseIf ? "else " : "")}if ({condition})");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
EmitBlock(ifNode.Body);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
ifNode.Else?.Match
|
||||
(
|
||||
elseIfNode => EmitIf(elseIfNode, true),
|
||||
elseNode =>
|
||||
{
|
||||
_writer.WriteLine("else");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
EmitBlock(elseNode);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private void EmitReturn(ReturnNode returnNode)
|
||||
{
|
||||
if (returnNode.Value == null)
|
||||
{
|
||||
var blockDefers = _deferStack.Peek();
|
||||
for (var i = blockDefers.Count - 1; i >= 0; i--)
|
||||
{
|
||||
EmitStatement(blockDefers[i].Statement);
|
||||
}
|
||||
|
||||
_writer.WriteLine("return;");
|
||||
}
|
||||
else
|
||||
{
|
||||
var returnValue = EmitExpression(returnNode.Value);
|
||||
|
||||
if (_deferStack.Peek().Count != 0)
|
||||
{
|
||||
var tmp = NewTmp();
|
||||
_writer.WriteLine($"{CType.Create(returnNode.Value.Type, tmp)} = {returnValue};");
|
||||
|
||||
var blockDefers = _deferStack.Peek();
|
||||
for (var i = blockDefers.Count - 1; i >= 0; i--)
|
||||
{
|
||||
EmitStatement(blockDefers[i].Statement);
|
||||
}
|
||||
|
||||
EmitLine(returnNode.Tokens.FirstOrDefault());
|
||||
_writer.WriteLine($"return {tmp};");
|
||||
}
|
||||
else
|
||||
{
|
||||
EmitLine(returnNode.Tokens.FirstOrDefault());
|
||||
_writer.WriteLine($"return {returnValue};");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EmitStatementFuncCall(StatementFuncCallNode statementFuncCallNode)
|
||||
{
|
||||
var funcCall = EmitFuncCall(statementFuncCallNode.FuncCall);
|
||||
_writer.WriteLine($"{funcCall};");
|
||||
}
|
||||
|
||||
private void EmitVariableDeclaration(VariableDeclarationNode variableDeclarationNode)
|
||||
{
|
||||
if (variableDeclarationNode.Assignment != null)
|
||||
{
|
||||
var value = EmitExpression(variableDeclarationNode.Assignment);
|
||||
_writer.WriteLine($"{CType.Create(variableDeclarationNode.Type, variableDeclarationNode.Name)} = {value};");
|
||||
}
|
||||
else
|
||||
{
|
||||
_writer.WriteLine($"{CType.Create(variableDeclarationNode.Type, variableDeclarationNode.Name)};");
|
||||
}
|
||||
}
|
||||
|
||||
private void EmitWhile(WhileNode whileNode)
|
||||
{
|
||||
var condition = EmitExpression(whileNode.Condition);
|
||||
_writer.WriteLine($"while ({condition})");
|
||||
_writer.WriteLine("{");
|
||||
using (_writer.Indent())
|
||||
{
|
||||
EmitBlock(whileNode.Body);
|
||||
}
|
||||
|
||||
_writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private string EmitExpression(ExpressionNode expressionNode)
|
||||
{
|
||||
if (expressionNode is IntermediateExpression)
|
||||
{
|
||||
throw new UnreachableException("Type checker fucked up");
|
||||
}
|
||||
|
||||
var expr = expressionNode switch
|
||||
{
|
||||
ArrayIndexAccessNode arrayIndexAccessNode => EmitArrayIndexAccess(arrayIndexAccessNode),
|
||||
ArrayInitializerNode arrayInitializerNode => EmitArrayInitializer(arrayInitializerNode),
|
||||
BinaryExpressionNode binaryExpressionNode => EmitBinaryExpression(binaryExpressionNode),
|
||||
BoolLiteralNode boolLiteralNode => boolLiteralNode.Value ? "true" : "false",
|
||||
ConstArrayIndexAccessNode constArrayIndexAccessNode => EmitConstArrayIndexAccess(constArrayIndexAccessNode),
|
||||
ConstArrayInitializerNode constArrayInitializerNode => EmitConstArrayInitializer(constArrayInitializerNode),
|
||||
ConstArrayToSliceNode constArrayToSliceNode => EmitConstArrayToSlice(constArrayToSliceNode),
|
||||
ConvertCStringToStringNode convertCStringToStringNode => EmitConvertCStringToString(convertCStringToStringNode),
|
||||
ConvertFloatNode convertFloatNode => EmitConvertFloat(convertFloatNode),
|
||||
ConvertIntNode convertIntNode => EmitConvertInt(convertIntNode),
|
||||
CStringLiteralNode cStringLiteralNode => $"\"{cStringLiteralNode.Value}\"",
|
||||
DereferenceNode dereferenceNode => EmitDereference(dereferenceNode),
|
||||
Float32LiteralNode float32LiteralNode => EmitFloat32Literal(float32LiteralNode),
|
||||
Float64LiteralNode float64LiteralNode => EmitFloat64Literal(float64LiteralNode),
|
||||
FloatToIntBuiltinNode floatToIntBuiltinNode => EmitFloatToIntBuiltin(floatToIntBuiltinNode),
|
||||
FuncCallNode funcCallNode => EmitFuncCall(funcCallNode),
|
||||
FuncIdentifierNode funcIdentifierNode => FuncName(funcIdentifierNode.Module, funcIdentifierNode.Name, funcIdentifierNode.ExternSymbol),
|
||||
AddressOfNode addressOfNode => EmitAddressOf(addressOfNode),
|
||||
SizeBuiltinNode sizeBuiltinNode => $"sizeof({CType.Create(sizeBuiltinNode.TargetType)})",
|
||||
SliceIndexAccessNode sliceIndexAccessNode => EmitSliceArrayIndexAccess(sliceIndexAccessNode),
|
||||
StringLiteralNode stringLiteralNode => EmitStringLiteral(stringLiteralNode),
|
||||
StructFieldAccessNode structFieldAccessNode => EmitStructFieldAccess(structFieldAccessNode),
|
||||
StructInitializerNode structInitializerNode => EmitStructInitializer(structInitializerNode),
|
||||
I8LiteralNode i8LiteralNode => EmitI8Literal(i8LiteralNode),
|
||||
I16LiteralNode i16LiteralNode => EmitI16Literal(i16LiteralNode),
|
||||
I32LiteralNode i32LiteralNode => EmitI32Literal(i32LiteralNode),
|
||||
I64LiteralNode i64LiteralNode => EmitI64Literal(i64LiteralNode),
|
||||
U8LiteralNode u8LiteralNode => EmitU8Literal(u8LiteralNode),
|
||||
U16LiteralNode u16LiteralNode => EmitU16Literal(u16LiteralNode),
|
||||
U32LiteralNode u32LiteralNode => EmitU32Literal(u32LiteralNode),
|
||||
U64LiteralNode u64LiteralNode => EmitU64Literal(u64LiteralNode),
|
||||
UnaryExpressionNode unaryExpressionNode => EmitUnaryExpression(unaryExpressionNode),
|
||||
VariableIdentifierNode variableIdentifierNode => variableIdentifierNode.Name,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(expressionNode))
|
||||
};
|
||||
|
||||
return $"({expr})";
|
||||
}
|
||||
|
||||
private string EmitArrayIndexAccess(ArrayIndexAccessNode arrayIndexAccessNode)
|
||||
{
|
||||
var target = EmitExpression(arrayIndexAccessNode.Target);
|
||||
var index = EmitExpression(arrayIndexAccessNode.Index);
|
||||
return $"{target}[{index}]";
|
||||
}
|
||||
|
||||
private string EmitArrayInitializer(ArrayInitializerNode arrayInitializerNode)
|
||||
{
|
||||
var values = new List<string>();
|
||||
foreach (var value in arrayInitializerNode.Values)
|
||||
{
|
||||
values.Add(EmitExpression(value));
|
||||
}
|
||||
|
||||
var arrayType = (NubArrayType)arrayInitializerNode.Type;
|
||||
return $"({CType.Create(arrayType.ElementType)}[]){{{string.Join(", ", values)}}}";
|
||||
}
|
||||
|
||||
private string EmitBinaryExpression(BinaryExpressionNode binaryExpressionNode)
|
||||
{
|
||||
var left = EmitExpression(binaryExpressionNode.Left);
|
||||
var right = EmitExpression(binaryExpressionNode.Right);
|
||||
|
||||
var op = binaryExpressionNode.Operator switch
|
||||
{
|
||||
BinaryOperator.Plus => "+",
|
||||
BinaryOperator.Minus => "-",
|
||||
BinaryOperator.Multiply => "*",
|
||||
BinaryOperator.Divide => "/",
|
||||
BinaryOperator.Modulo => "%",
|
||||
BinaryOperator.Equal => "==",
|
||||
BinaryOperator.NotEqual => "!=",
|
||||
BinaryOperator.LessThan => "<",
|
||||
BinaryOperator.LessThanOrEqual => "<=",
|
||||
BinaryOperator.GreaterThan => ">",
|
||||
BinaryOperator.GreaterThanOrEqual => ">=",
|
||||
BinaryOperator.LogicalAnd => "&&",
|
||||
BinaryOperator.LogicalOr => "||",
|
||||
BinaryOperator.BitwiseAnd => "&",
|
||||
BinaryOperator.BitwiseOr => "|",
|
||||
BinaryOperator.BitwiseXor => "^",
|
||||
BinaryOperator.LeftShift => "<<",
|
||||
BinaryOperator.RightShift => ">>",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
|
||||
return $"{left} {op} {right}";
|
||||
}
|
||||
|
||||
private string EmitConstArrayIndexAccess(ConstArrayIndexAccessNode constArrayIndexAccessNode)
|
||||
{
|
||||
var target = EmitExpression(constArrayIndexAccessNode.Target);
|
||||
var index = EmitExpression(constArrayIndexAccessNode.Index);
|
||||
// todo(nub31): We can emit bounds checking here
|
||||
return $"{target}[{index}]";
|
||||
}
|
||||
|
||||
private string EmitConstArrayInitializer(ConstArrayInitializerNode arrayInitializerNode)
|
||||
{
|
||||
var values = new List<string>();
|
||||
foreach (var value in arrayInitializerNode.Values)
|
||||
{
|
||||
values.Add(EmitExpression(value));
|
||||
}
|
||||
|
||||
var arrayType = (NubConstArrayType)arrayInitializerNode.Type;
|
||||
return $"({CType.Create(arrayType.ElementType)}[{arrayType.Size}]){{{string.Join(", ", values)}}}";
|
||||
}
|
||||
|
||||
private string EmitConstArrayToSlice(ConstArrayToSliceNode constArrayToSliceNode)
|
||||
{
|
||||
var arrayType = (NubConstArrayType)constArrayToSliceNode.Array.Type;
|
||||
var array = EmitExpression(constArrayToSliceNode.Array);
|
||||
return $"(slice){{.length = {arrayType.Size}, .data = (void*){array}}}";
|
||||
}
|
||||
|
||||
private string EmitConvertCStringToString(ConvertCStringToStringNode convertCStringToStringNode)
|
||||
{
|
||||
var value = EmitExpression(convertCStringToStringNode.Value);
|
||||
return $"(string){{.length = strlen({value}), .data = {value}}}";
|
||||
}
|
||||
|
||||
private string EmitConvertFloat(ConvertFloatNode convertFloatNode)
|
||||
{
|
||||
var value = EmitExpression(convertFloatNode.Value);
|
||||
var targetCast = convertFloatNode.TargetWidth switch
|
||||
{
|
||||
32 => "f32",
|
||||
64 => "f64",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
|
||||
return $"({targetCast}){value}";
|
||||
}
|
||||
|
||||
private string EmitConvertInt(ConvertIntNode convertIntNode)
|
||||
{
|
||||
var value = EmitExpression(convertIntNode.Value);
|
||||
var targetType = convertIntNode.TargetWidth switch
|
||||
{
|
||||
8 => convertIntNode.TargetSignedness ? "int8_t" : "uint8_t",
|
||||
16 => convertIntNode.TargetSignedness ? "int16_t" : "uint16_t",
|
||||
32 => convertIntNode.TargetSignedness ? "int32_t" : "uint32_t",
|
||||
64 => convertIntNode.TargetSignedness ? "int64_t" : "uint64_t",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
return $"({targetType}){value}";
|
||||
}
|
||||
|
||||
private string EmitDereference(DereferenceNode dereferenceNode)
|
||||
{
|
||||
var pointer = EmitExpression(dereferenceNode.Target);
|
||||
return $"*{pointer}";
|
||||
}
|
||||
|
||||
private string EmitFloat32Literal(Float32LiteralNode float32LiteralNode)
|
||||
{
|
||||
var str = float32LiteralNode.Value.ToString("G9", System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (!str.Contains('.') && !str.Contains('e') && !str.Contains('E'))
|
||||
{
|
||||
str += ".0";
|
||||
}
|
||||
|
||||
return str + "f";
|
||||
}
|
||||
|
||||
private string EmitFloat64Literal(Float64LiteralNode float64LiteralNode)
|
||||
{
|
||||
var str = float64LiteralNode.Value.ToString("G17", System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (!str.Contains('.') && !str.Contains('e') && !str.Contains('E'))
|
||||
{
|
||||
str += ".0";
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
private string EmitFloatToIntBuiltin(FloatToIntBuiltinNode floatToIntBuiltinNode)
|
||||
{
|
||||
var value = EmitExpression(floatToIntBuiltinNode.Value);
|
||||
var targetType = floatToIntBuiltinNode.TargetType.Width switch
|
||||
{
|
||||
8 => floatToIntBuiltinNode.TargetType.Signed ? "int8_t" : "uint8_t",
|
||||
16 => floatToIntBuiltinNode.TargetType.Signed ? "int16_t" : "uint16_t",
|
||||
32 => floatToIntBuiltinNode.TargetType.Signed ? "int32_t" : "uint32_t",
|
||||
64 => floatToIntBuiltinNode.TargetType.Signed ? "int64_t" : "uint64_t",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
return $"({targetType}){value}";
|
||||
}
|
||||
|
||||
private string EmitFuncCall(FuncCallNode funcCallNode)
|
||||
{
|
||||
var name = EmitExpression(funcCallNode.Expression);
|
||||
var parameterNames = funcCallNode.Parameters.Select(EmitExpression).ToList();
|
||||
return $"{name}({string.Join(", ", parameterNames)})";
|
||||
}
|
||||
|
||||
private string EmitAddressOf(AddressOfNode addressOfNode)
|
||||
{
|
||||
var value = EmitExpression(addressOfNode.LValue);
|
||||
return $"&{value}";
|
||||
}
|
||||
|
||||
private string EmitSliceArrayIndexAccess(SliceIndexAccessNode sliceIndexAccessNode)
|
||||
{
|
||||
var targetType = (NubSliceType)sliceIndexAccessNode.Target.Type;
|
||||
var target = EmitExpression(sliceIndexAccessNode.Target);
|
||||
var index = EmitExpression(sliceIndexAccessNode.Index);
|
||||
// todo(nub31): We can emit bounds checking here
|
||||
return $"(({CType.Create(targetType.ElementType)}*){target}.data)[{index}]";
|
||||
}
|
||||
|
||||
private string EmitStringLiteral(StringLiteralNode stringLiteralNode)
|
||||
{
|
||||
var length = Encoding.UTF8.GetByteCount(stringLiteralNode.Value);
|
||||
return $"(string){{.length = {length}, .data = \"{stringLiteralNode.Value}\"}}";
|
||||
}
|
||||
|
||||
private string EmitStructFieldAccess(StructFieldAccessNode structFieldAccessNode)
|
||||
{
|
||||
var structExpr = EmitExpression(structFieldAccessNode.Target);
|
||||
return $"{structExpr}.{structFieldAccessNode.Field}";
|
||||
}
|
||||
|
||||
private string EmitStructInitializer(StructInitializerNode structInitializerNode)
|
||||
{
|
||||
var initValues = new List<string>();
|
||||
foreach (var initializer in structInitializerNode.Initializers)
|
||||
{
|
||||
var value = EmitExpression(initializer.Value);
|
||||
initValues.Add($".{initializer.Key} = {value}");
|
||||
}
|
||||
|
||||
var initString = initValues.Count == 0
|
||||
? "0"
|
||||
: string.Join(", ", initValues);
|
||||
|
||||
return $"({CType.Create(structInitializerNode.Type)}){{{initString}}}";
|
||||
}
|
||||
|
||||
private string EmitI8Literal(I8LiteralNode i8LiteralNode)
|
||||
{
|
||||
return i8LiteralNode.Value.ToString();
|
||||
}
|
||||
|
||||
private string EmitI16Literal(I16LiteralNode i16LiteralNode)
|
||||
{
|
||||
return i16LiteralNode.Value.ToString();
|
||||
}
|
||||
|
||||
private string EmitI32Literal(I32LiteralNode i32LiteralNode)
|
||||
{
|
||||
return i32LiteralNode.Value.ToString();
|
||||
}
|
||||
|
||||
private string EmitI64Literal(I64LiteralNode i64LiteralNode)
|
||||
{
|
||||
return i64LiteralNode.Value + "LL";
|
||||
}
|
||||
|
||||
private string EmitU8Literal(U8LiteralNode u8LiteralNode)
|
||||
{
|
||||
return u8LiteralNode.Value.ToString();
|
||||
}
|
||||
|
||||
private string EmitU16Literal(U16LiteralNode u16LiteralNode)
|
||||
{
|
||||
return u16LiteralNode.Value.ToString();
|
||||
}
|
||||
|
||||
private string EmitU32Literal(U32LiteralNode u32LiteralNode)
|
||||
{
|
||||
return u32LiteralNode.Value.ToString();
|
||||
}
|
||||
|
||||
private string EmitU64Literal(U64LiteralNode u64LiteralNode)
|
||||
{
|
||||
return u64LiteralNode.Value + "ULL";
|
||||
}
|
||||
|
||||
private string EmitUnaryExpression(UnaryExpressionNode unaryExpressionNode)
|
||||
{
|
||||
var value = EmitExpression(unaryExpressionNode.Operand);
|
||||
|
||||
return unaryExpressionNode.Operator switch
|
||||
{
|
||||
UnaryOperator.Negate => $"-{value}",
|
||||
UnaryOperator.Invert => $"!{value}",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
}
|
||||
|
||||
private void EmitBlock(BlockNode blockNode)
|
||||
{
|
||||
_deferStack.Push([]);
|
||||
|
||||
foreach (var statementNode in blockNode.Statements)
|
||||
{
|
||||
EmitStatement(statementNode);
|
||||
}
|
||||
|
||||
var blockDefers = _deferStack.Pop();
|
||||
for (var i = blockDefers.Count - 1; i >= 0; i--)
|
||||
{
|
||||
EmitStatement(blockDefers[i].Statement);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
using System.Text;
|
||||
|
||||
namespace NubLang.Generation;
|
||||
|
||||
internal class IndentedTextWriter
|
||||
{
|
||||
private readonly StringBuilder _builder = new();
|
||||
private int _indentLevel;
|
||||
|
||||
public IDisposable Indent()
|
||||
{
|
||||
_indentLevel++;
|
||||
return new IndentScope(this);
|
||||
}
|
||||
|
||||
public void WriteLine(string text)
|
||||
{
|
||||
WriteIndent();
|
||||
_builder.AppendLine(text);
|
||||
}
|
||||
|
||||
public void Write(string text)
|
||||
{
|
||||
WriteIndent();
|
||||
_builder.Append(text);
|
||||
}
|
||||
|
||||
public void WriteLine()
|
||||
{
|
||||
_builder.AppendLine();
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return _builder.ToString();
|
||||
}
|
||||
|
||||
private void WriteIndent()
|
||||
{
|
||||
if (_builder.Length > 0)
|
||||
{
|
||||
var lastChar = _builder[^1];
|
||||
if (lastChar != '\n' && lastChar != '\r')
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0; i < _indentLevel; i++)
|
||||
{
|
||||
_builder.Append(" ");
|
||||
}
|
||||
}
|
||||
|
||||
private class IndentScope : IDisposable
|
||||
{
|
||||
private readonly IndentedTextWriter _writer;
|
||||
private bool _disposed;
|
||||
|
||||
public IndentScope(IndentedTextWriter writer)
|
||||
{
|
||||
_writer = writer;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_writer._indentLevel--;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
namespace NubLang.Syntax;
|
||||
|
||||
public sealed class Module
|
||||
{
|
||||
public static Dictionary<string, Module> Collect(List<SyntaxTree> syntaxTrees)
|
||||
{
|
||||
var modules = new Dictionary<string, Module>();
|
||||
foreach (var syntaxTree in syntaxTrees)
|
||||
{
|
||||
if (!modules.TryGetValue(syntaxTree.ModuleName, out var module))
|
||||
{
|
||||
module = new Module();
|
||||
modules.Add(syntaxTree.ModuleName, module);
|
||||
}
|
||||
|
||||
module._definitions.AddRange(syntaxTree.Definitions);
|
||||
}
|
||||
|
||||
return modules;
|
||||
}
|
||||
|
||||
private readonly List<DefinitionSyntax> _definitions = [];
|
||||
|
||||
public List<StructSyntax> Structs(bool includePrivate)
|
||||
{
|
||||
return _definitions
|
||||
.OfType<StructSyntax>()
|
||||
.Where(x => x.Exported || includePrivate)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public List<FuncSyntax> Functions(bool includePrivate)
|
||||
{
|
||||
return _definitions
|
||||
.OfType<FuncSyntax>()
|
||||
.Where(x => x.Exported || includePrivate)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public List<EnumSyntax> Enums(bool includePrivate)
|
||||
{
|
||||
return _definitions
|
||||
.OfType<EnumSyntax>()
|
||||
.Where(x => x.Exported || includePrivate)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -1,963 +0,0 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using NubLang.Diagnostics;
|
||||
|
||||
namespace NubLang.Syntax;
|
||||
|
||||
public sealed class Parser
|
||||
{
|
||||
private List<Token> _tokens = [];
|
||||
private int _tokenIndex;
|
||||
|
||||
private Token? CurrentToken => _tokenIndex < _tokens.Count ? _tokens[_tokenIndex] : null;
|
||||
private bool HasToken => CurrentToken != null;
|
||||
|
||||
public List<Diagnostic> Diagnostics { get; } = [];
|
||||
|
||||
public SyntaxTree Parse(List<Token> tokens)
|
||||
{
|
||||
Diagnostics.Clear();
|
||||
_tokens = tokens;
|
||||
_tokenIndex = 0;
|
||||
|
||||
string? moduleName = null;
|
||||
var imports = new List<string>();
|
||||
var definitions = new List<DefinitionSyntax>();
|
||||
|
||||
while (HasToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Import))
|
||||
{
|
||||
var name = ExpectStringLiteral();
|
||||
if (imports.Contains(name.Value))
|
||||
{
|
||||
Diagnostics.Add(Diagnostic
|
||||
.Warning($"Module {name.Value} is imported twice")
|
||||
.At(name)
|
||||
.WithHelp($"Remove duplicate import \"{name.Value}\"")
|
||||
.Build());
|
||||
}
|
||||
else
|
||||
{
|
||||
imports.Add(name.Value);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.Module))
|
||||
{
|
||||
if (moduleName != null)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Module is declared more than once")
|
||||
.At(CurrentToken)
|
||||
.WithHelp("Remove duplicate module declaration")
|
||||
.Build());
|
||||
}
|
||||
|
||||
moduleName = ExpectStringLiteral().Value;
|
||||
continue;
|
||||
}
|
||||
|
||||
var exported = TryExpectSymbol(Symbol.Export);
|
||||
|
||||
if (TryExpectSymbol(Symbol.Extern))
|
||||
{
|
||||
var externSymbol = ExpectStringLiteral();
|
||||
ExpectSymbol(Symbol.Func);
|
||||
definitions.Add(ParseFunc(startIndex, exported, externSymbol.Value));
|
||||
continue;
|
||||
}
|
||||
|
||||
var keyword = ExpectSymbol();
|
||||
DefinitionSyntax definition = keyword.Symbol switch
|
||||
{
|
||||
Symbol.Func => ParseFunc(startIndex, exported, null),
|
||||
Symbol.Struct => ParseStruct(startIndex, exported),
|
||||
Symbol.Enum => ParseEnum(startIndex, exported),
|
||||
_ => throw new ParseException(Diagnostic
|
||||
.Error($"Expected 'func', 'struct', 'enum', 'import' or 'module' but found '{keyword.Symbol}'")
|
||||
.WithHelp("Valid top level statements are 'func', 'struct', 'enum', 'import' and 'module'")
|
||||
.At(keyword)
|
||||
.Build())
|
||||
};
|
||||
|
||||
definitions.Add(definition);
|
||||
}
|
||||
catch (ParseException e)
|
||||
{
|
||||
Diagnostics.Add(e.Diagnostic);
|
||||
while (HasToken)
|
||||
{
|
||||
if (CurrentToken is SymbolToken { Symbol: Symbol.Extern or Symbol.Func or Symbol.Struct })
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new SyntaxTree(definitions, moduleName ?? "default", imports);
|
||||
}
|
||||
|
||||
private FuncParameterSyntax ParseFuncParameter()
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
var name = ExpectIdentifier();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var type = ParseType();
|
||||
|
||||
return new FuncParameterSyntax(GetTokens(startIndex), name.Value, type);
|
||||
}
|
||||
|
||||
private FuncSyntax ParseFunc(int startIndex, bool exported, string? externSymbol)
|
||||
{
|
||||
var name = ExpectIdentifier();
|
||||
List<FuncParameterSyntax> parameters = [];
|
||||
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseParen))
|
||||
{
|
||||
parameters.Add(ParseFuncParameter());
|
||||
|
||||
if (!TryExpectSymbol(Symbol.Comma))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var returnType = TryExpectSymbol(Symbol.Colon) ? ParseType() : new VoidTypeSyntax([]);
|
||||
|
||||
var prototype = new FuncPrototypeSyntax(GetTokens(startIndex), name.Value, exported, externSymbol, parameters, returnType);
|
||||
|
||||
BlockSyntax? body = null;
|
||||
var bodyStartIndex = _tokenIndex;
|
||||
if (TryExpectSymbol(Symbol.OpenBrace))
|
||||
{
|
||||
body = ParseBlock(bodyStartIndex);
|
||||
}
|
||||
|
||||
return new FuncSyntax(GetTokens(startIndex), prototype, body);
|
||||
}
|
||||
|
||||
private StructSyntax ParseStruct(int startIndex, bool exported)
|
||||
{
|
||||
var name = ExpectIdentifier();
|
||||
|
||||
ExpectSymbol(Symbol.OpenBrace);
|
||||
|
||||
List<StructFieldSyntax> fields = [];
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||
{
|
||||
var memberStartIndex = _tokenIndex;
|
||||
|
||||
var fieldName = ExpectIdentifier().Value;
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var fieldType = ParseType();
|
||||
|
||||
ExpressionSyntax? fieldValue = null;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Assign))
|
||||
{
|
||||
fieldValue = ParseExpression();
|
||||
}
|
||||
|
||||
fields.Add(new StructFieldSyntax(GetTokens(memberStartIndex), fieldName, fieldType, fieldValue));
|
||||
}
|
||||
|
||||
return new StructSyntax(GetTokens(startIndex), name.Value, exported, fields);
|
||||
}
|
||||
|
||||
private EnumSyntax ParseEnum(int startIndex, bool exported)
|
||||
{
|
||||
var name = ExpectIdentifier();
|
||||
|
||||
TypeSyntax? type = null;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
{
|
||||
type = ParseType();
|
||||
}
|
||||
|
||||
List<EnumFieldSyntax> fields = [];
|
||||
|
||||
ExpectSymbol(Symbol.OpenBrace);
|
||||
|
||||
long value = -1;
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||
{
|
||||
var memberStartIndex = _tokenIndex;
|
||||
var fieldName = ExpectIdentifier().Value;
|
||||
long fieldValue;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Assign))
|
||||
{
|
||||
if (!TryExpectIntLiteral(out var intLiteralToken))
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Value of enum field must be an integer literal")
|
||||
.At(CurrentToken)
|
||||
.Build());
|
||||
}
|
||||
|
||||
fieldValue = Convert.ToInt64(intLiteralToken.Value, intLiteralToken.Base);
|
||||
value = fieldValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
fieldValue = value + 1;
|
||||
value = fieldValue;
|
||||
}
|
||||
|
||||
fields.Add(new EnumFieldSyntax(GetTokens(memberStartIndex), fieldName, fieldValue));
|
||||
}
|
||||
|
||||
return new EnumSyntax(GetTokens(startIndex), name.Value, exported, type, fields);
|
||||
}
|
||||
|
||||
private StatementSyntax ParseStatement()
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
|
||||
if (TryExpectSymbol(out var symbol))
|
||||
{
|
||||
switch (symbol)
|
||||
{
|
||||
case Symbol.OpenBrace:
|
||||
return ParseBlock(startIndex);
|
||||
case Symbol.Return:
|
||||
return ParseReturn(startIndex);
|
||||
case Symbol.If:
|
||||
return ParseIf(startIndex);
|
||||
case Symbol.While:
|
||||
return ParseWhile(startIndex);
|
||||
case Symbol.For:
|
||||
return ParseFor(startIndex);
|
||||
case Symbol.Let:
|
||||
return ParseVariableDeclaration(startIndex);
|
||||
case Symbol.Defer:
|
||||
return ParseDefer(startIndex);
|
||||
case Symbol.Break:
|
||||
return new BreakSyntax(GetTokens(startIndex));
|
||||
case Symbol.Continue:
|
||||
return new ContinueSyntax(GetTokens(startIndex));
|
||||
}
|
||||
}
|
||||
|
||||
var expr = ParseExpression();
|
||||
|
||||
if (TryExpectSymbol(Symbol.Assign))
|
||||
{
|
||||
var value = ParseExpression();
|
||||
return new AssignmentSyntax(GetTokens(startIndex), expr, value);
|
||||
}
|
||||
|
||||
return new StatementExpressionSyntax(GetTokens(startIndex), expr);
|
||||
}
|
||||
|
||||
private VariableDeclarationSyntax ParseVariableDeclaration(int startIndex)
|
||||
{
|
||||
var name = ExpectIdentifier().Value;
|
||||
|
||||
TypeSyntax? explicitType = null;
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
{
|
||||
explicitType = ParseType();
|
||||
}
|
||||
|
||||
ExpressionSyntax? assignment = null;
|
||||
if (TryExpectSymbol(Symbol.Assign))
|
||||
{
|
||||
assignment = ParseExpression();
|
||||
}
|
||||
|
||||
return new VariableDeclarationSyntax(GetTokens(startIndex), name, explicitType, assignment);
|
||||
}
|
||||
|
||||
private DeferSyntax ParseDefer(int startIndex)
|
||||
{
|
||||
var statement = ParseStatement();
|
||||
return new DeferSyntax(GetTokens(startIndex), statement);
|
||||
}
|
||||
|
||||
private ReturnSyntax ParseReturn(int startIndex)
|
||||
{
|
||||
ExpressionSyntax? value = null;
|
||||
|
||||
if (!TryExpectSymbol(Symbol.Semi))
|
||||
{
|
||||
value = ParseExpression();
|
||||
}
|
||||
|
||||
return new ReturnSyntax(GetTokens(startIndex), value);
|
||||
}
|
||||
|
||||
private IfSyntax ParseIf(int startIndex)
|
||||
{
|
||||
var condition = ParseExpression();
|
||||
var body = ParseBlock();
|
||||
|
||||
Variant<IfSyntax, BlockSyntax>? elseStatement = null;
|
||||
|
||||
var elseStartIndex = _tokenIndex;
|
||||
if (TryExpectSymbol(Symbol.Else))
|
||||
{
|
||||
if (TryExpectSymbol(Symbol.If))
|
||||
{
|
||||
elseStatement = (Variant<IfSyntax, BlockSyntax>)ParseIf(elseStartIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
elseStatement = (Variant<IfSyntax, BlockSyntax>)ParseBlock();
|
||||
}
|
||||
}
|
||||
|
||||
return new IfSyntax(GetTokens(startIndex), condition, body, elseStatement);
|
||||
}
|
||||
|
||||
private WhileSyntax ParseWhile(int startIndex)
|
||||
{
|
||||
var condition = ParseExpression();
|
||||
var body = ParseBlock();
|
||||
return new WhileSyntax(GetTokens(startIndex), condition, body);
|
||||
}
|
||||
|
||||
private ForSyntax ParseFor(int startIndex)
|
||||
{
|
||||
var itemName = ExpectIdentifier().Value;
|
||||
string? indexName = null;
|
||||
|
||||
if (TryExpectSymbol(Symbol.Comma))
|
||||
{
|
||||
indexName = ExpectIdentifier().Value;
|
||||
}
|
||||
|
||||
ExpectSymbol(Symbol.In);
|
||||
var target = ParseExpression();
|
||||
var body = ParseBlock();
|
||||
|
||||
return new ForSyntax(GetTokens(startIndex), itemName, indexName, target, body);
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParseExpression(int precedence = 0)
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
var left = ParsePrimaryExpression();
|
||||
|
||||
while (CurrentToken is SymbolToken symbolToken && TryGetBinaryOperator(symbolToken.Symbol, out var op) && GetBinaryOperatorPrecedence(op.Value) >= precedence)
|
||||
{
|
||||
Next();
|
||||
var right = ParseExpression(GetBinaryOperatorPrecedence(op.Value) + 1);
|
||||
left = new BinaryExpressionSyntax(GetTokens(startIndex), left, op.Value, right);
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private static int GetBinaryOperatorPrecedence(BinaryOperatorSyntax operatorSyntax)
|
||||
{
|
||||
return operatorSyntax switch
|
||||
{
|
||||
BinaryOperatorSyntax.Multiply => 10,
|
||||
BinaryOperatorSyntax.Divide => 10,
|
||||
BinaryOperatorSyntax.Modulo => 10,
|
||||
|
||||
BinaryOperatorSyntax.Plus => 9,
|
||||
BinaryOperatorSyntax.Minus => 9,
|
||||
|
||||
BinaryOperatorSyntax.LeftShift => 8,
|
||||
BinaryOperatorSyntax.RightShift => 8,
|
||||
|
||||
BinaryOperatorSyntax.GreaterThan => 7,
|
||||
BinaryOperatorSyntax.GreaterThanOrEqual => 7,
|
||||
BinaryOperatorSyntax.LessThan => 7,
|
||||
BinaryOperatorSyntax.LessThanOrEqual => 7,
|
||||
|
||||
BinaryOperatorSyntax.Equal => 7,
|
||||
BinaryOperatorSyntax.NotEqual => 7,
|
||||
|
||||
BinaryOperatorSyntax.BitwiseAnd => 6,
|
||||
BinaryOperatorSyntax.BitwiseXor => 5,
|
||||
BinaryOperatorSyntax.BitwiseOr => 4,
|
||||
|
||||
BinaryOperatorSyntax.LogicalAnd => 3,
|
||||
BinaryOperatorSyntax.LogicalOr => 2,
|
||||
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(operatorSyntax), operatorSyntax, null)
|
||||
};
|
||||
}
|
||||
|
||||
private bool TryGetBinaryOperator(Symbol symbol, [NotNullWhen(true)] out BinaryOperatorSyntax? binaryExpressionOperator)
|
||||
{
|
||||
switch (symbol)
|
||||
{
|
||||
case Symbol.Equal:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.Equal;
|
||||
return true;
|
||||
case Symbol.NotEqual:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.NotEqual;
|
||||
return true;
|
||||
case Symbol.LessThan:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.LessThan;
|
||||
return true;
|
||||
case Symbol.LessThanOrEqual:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.LessThanOrEqual;
|
||||
return true;
|
||||
case Symbol.GreaterThan:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.GreaterThan;
|
||||
return true;
|
||||
case Symbol.GreaterThanOrEqual:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.GreaterThanOrEqual;
|
||||
return true;
|
||||
case Symbol.And:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.LogicalAnd;
|
||||
return true;
|
||||
case Symbol.Or:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.LogicalOr;
|
||||
return true;
|
||||
case Symbol.Plus:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.Plus;
|
||||
return true;
|
||||
case Symbol.Minus:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.Minus;
|
||||
return true;
|
||||
case Symbol.Star:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.Multiply;
|
||||
return true;
|
||||
case Symbol.ForwardSlash:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.Divide;
|
||||
return true;
|
||||
case Symbol.Percent:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.Modulo;
|
||||
return true;
|
||||
case Symbol.LeftShift:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.LeftShift;
|
||||
return true;
|
||||
case Symbol.RightShift:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.RightShift;
|
||||
return true;
|
||||
case Symbol.Ampersand:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.BitwiseAnd;
|
||||
return true;
|
||||
case Symbol.Pipe:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.BitwiseOr;
|
||||
return true;
|
||||
case Symbol.Caret:
|
||||
binaryExpressionOperator = BinaryOperatorSyntax.BitwiseXor;
|
||||
return true;
|
||||
default:
|
||||
binaryExpressionOperator = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParsePrimaryExpression()
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
var token = ExpectToken();
|
||||
var expr = token switch
|
||||
{
|
||||
BoolLiteralToken boolLiteral => new BoolLiteralSyntax(GetTokens(startIndex), boolLiteral.Value),
|
||||
StringLiteralToken stringLiteral => new StringLiteralSyntax(GetTokens(startIndex), stringLiteral.Value),
|
||||
FloatLiteralToken floatLiteral => new FloatLiteralSyntax(GetTokens(startIndex), floatLiteral.Value),
|
||||
IntLiteralToken intLiteral => new IntLiteralSyntax(GetTokens(startIndex), intLiteral.Value, intLiteral.Base),
|
||||
IdentifierToken identifier => ParseIdentifier(startIndex, identifier),
|
||||
SymbolToken symbolToken => symbolToken.Symbol switch
|
||||
{
|
||||
Symbol.OpenParen => ParseParenthesizedExpression(),
|
||||
Symbol.Minus => new UnaryExpressionSyntax(GetTokens(startIndex), UnaryOperatorSyntax.Negate, ParsePrimaryExpression()),
|
||||
Symbol.Bang => new UnaryExpressionSyntax(GetTokens(startIndex), UnaryOperatorSyntax.Invert, ParsePrimaryExpression()),
|
||||
Symbol.OpenBracket => ParseArrayInitializer(startIndex),
|
||||
Symbol.OpenBrace => new StructInitializerSyntax(GetTokens(startIndex), null, ParseStructInitializerBody()),
|
||||
Symbol.Struct => ParseStructInitializer(startIndex),
|
||||
Symbol.At => ParseBuiltinFunction(startIndex),
|
||||
_ => throw new ParseException(Diagnostic
|
||||
.Error($"Unexpected symbol '{symbolToken.Symbol}' in expression")
|
||||
.WithHelp("Expected '(', '-', '!', '[' or '{'")
|
||||
.At(symbolToken)
|
||||
.Build())
|
||||
},
|
||||
_ => throw new ParseException(Diagnostic
|
||||
.Error($"Unexpected token '{token.GetType().Name}' in expression")
|
||||
.WithHelp("Expected literal, identifier, or parenthesized expression")
|
||||
.At(token)
|
||||
.Build())
|
||||
};
|
||||
|
||||
return ParsePostfixOperators(expr);
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParseBuiltinFunction(int startIndex)
|
||||
{
|
||||
var name = ExpectIdentifier();
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
|
||||
switch (name.Value)
|
||||
{
|
||||
case "size":
|
||||
{
|
||||
var type = ParseType();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
return new SizeBuiltinSyntax(GetTokens(startIndex), type);
|
||||
}
|
||||
case "interpret":
|
||||
{
|
||||
var type = ParseType();
|
||||
ExpectSymbol(Symbol.Comma);
|
||||
var expression = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
return new InterpretBuiltinSyntax(GetTokens(startIndex), type, expression);
|
||||
}
|
||||
case "floatToInt":
|
||||
{
|
||||
var type = ParseType();
|
||||
ExpectSymbol(Symbol.Comma);
|
||||
var expression = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
return new FloatToIntBuiltinSyntax(GetTokens(startIndex), type, expression);
|
||||
}
|
||||
default:
|
||||
{
|
||||
throw new ParseException(Diagnostic.Error($"Unknown builtin {name.Value}").At(name).Build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParseIdentifier(int startIndex, IdentifierToken identifier)
|
||||
{
|
||||
if (TryExpectSymbol(Symbol.DoubleColon))
|
||||
{
|
||||
var name = ExpectIdentifier();
|
||||
return new ModuleIdentifierSyntax(GetTokens(startIndex), identifier.Value, name.Value);
|
||||
}
|
||||
|
||||
return new LocalIdentifierSyntax(GetTokens(startIndex), identifier.Value);
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParseParenthesizedExpression()
|
||||
{
|
||||
var expression = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
return expression;
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParsePostfixOperators(ExpressionSyntax expr)
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
while (HasToken)
|
||||
{
|
||||
if (TryExpectSymbol(Symbol.Ampersand))
|
||||
{
|
||||
expr = new AddressOfSyntax(GetTokens(startIndex), expr);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.Caret))
|
||||
{
|
||||
expr = new DereferenceSyntax(GetTokens(startIndex), expr);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.Period))
|
||||
{
|
||||
var member = ExpectIdentifier().Value;
|
||||
expr = new MemberAccessSyntax(GetTokens(startIndex), expr, member);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.OpenBracket))
|
||||
{
|
||||
var index = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseBracket);
|
||||
expr = new ArrayIndexAccessSyntax(GetTokens(startIndex), expr, index);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.OpenParen))
|
||||
{
|
||||
var parameters = new List<ExpressionSyntax>();
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseParen))
|
||||
{
|
||||
parameters.Add(ParseExpression());
|
||||
if (!TryExpectSymbol(Symbol.Comma))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
expr = new FuncCallSyntax(GetTokens(startIndex), expr, parameters);
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return expr;
|
||||
}
|
||||
|
||||
private ExpressionSyntax ParseArrayInitializer(int startIndex)
|
||||
{
|
||||
var values = new List<ExpressionSyntax>();
|
||||
while (!TryExpectSymbol(Symbol.CloseBracket))
|
||||
{
|
||||
values.Add(ParseExpression());
|
||||
if (!TryExpectSymbol(Symbol.Comma))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseBracket);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayInitializerSyntax(GetTokens(startIndex), values);
|
||||
}
|
||||
|
||||
private StructInitializerSyntax ParseStructInitializer(int startIndex)
|
||||
{
|
||||
TypeSyntax? type = null;
|
||||
if (!TryExpectSymbol(Symbol.OpenBrace))
|
||||
{
|
||||
type = ParseType();
|
||||
ExpectSymbol(Symbol.OpenBrace);
|
||||
}
|
||||
|
||||
var initializers = ParseStructInitializerBody();
|
||||
|
||||
return new StructInitializerSyntax(GetTokens(startIndex), type, initializers);
|
||||
}
|
||||
|
||||
private Dictionary<string, ExpressionSyntax> ParseStructInitializerBody()
|
||||
{
|
||||
Dictionary<string, ExpressionSyntax> initializers = [];
|
||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||
{
|
||||
var name = ExpectIdentifier().Value;
|
||||
ExpectSymbol(Symbol.Assign);
|
||||
var value = ParseExpression();
|
||||
initializers.Add(name, value);
|
||||
}
|
||||
|
||||
return initializers;
|
||||
}
|
||||
|
||||
private BlockSyntax ParseBlock()
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
ExpectSymbol(Symbol.OpenBrace);
|
||||
return ParseBlock(startIndex);
|
||||
}
|
||||
|
||||
private BlockSyntax ParseBlock(int startIndex)
|
||||
{
|
||||
List<StatementSyntax> statements = [];
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||
{
|
||||
try
|
||||
{
|
||||
statements.Add(ParseStatement());
|
||||
}
|
||||
catch (ParseException ex)
|
||||
{
|
||||
Diagnostics.Add(ex.Diagnostic);
|
||||
if (HasToken)
|
||||
{
|
||||
Next();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new BlockSyntax(GetTokens(startIndex), statements);
|
||||
}
|
||||
|
||||
private TypeSyntax ParseType()
|
||||
{
|
||||
var startIndex = _tokenIndex;
|
||||
if (TryExpectIdentifier(out var name))
|
||||
{
|
||||
if (name.Value[0] == 'u' && int.TryParse(name.Value[1..], out var size))
|
||||
{
|
||||
if (size is not 8 and not 16 and not 32 and not 64)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Arbitrary uint size is not supported")
|
||||
.WithHelp("Use u8, u16, u32 or u64")
|
||||
.At(name)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return new IntTypeSyntax(GetTokens(startIndex), false, size);
|
||||
}
|
||||
|
||||
if (name.Value[0] == 'i' && int.TryParse(name.Value[1..], out size))
|
||||
{
|
||||
if (size is not 8 and not 16 and not 32 and not 64)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Arbitrary int size is not supported")
|
||||
.WithHelp("Use i8, i16, i32 or i64")
|
||||
.At(name)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return new IntTypeSyntax(GetTokens(startIndex), true, size);
|
||||
}
|
||||
|
||||
if (name.Value[0] == 'f' && int.TryParse(name.Value[1..], out size))
|
||||
{
|
||||
if (size is not 32 and not 64)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Arbitrary float size is not supported")
|
||||
.WithHelp("Use f32 or f64")
|
||||
.At(name)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return new FloatTypeSyntax(GetTokens(startIndex), size);
|
||||
}
|
||||
|
||||
switch (name.Value)
|
||||
{
|
||||
case "void":
|
||||
return new VoidTypeSyntax(GetTokens(startIndex));
|
||||
case "string":
|
||||
return new StringTypeSyntax(GetTokens(startIndex));
|
||||
case "cstring":
|
||||
return new CStringTypeSyntax(GetTokens(startIndex));
|
||||
case "bool":
|
||||
return new BoolTypeSyntax(GetTokens(startIndex));
|
||||
default:
|
||||
{
|
||||
string? module = null;
|
||||
|
||||
if (TryExpectSymbol(Symbol.DoubleColon))
|
||||
{
|
||||
var customTypeName = ExpectIdentifier();
|
||||
module = name.Value;
|
||||
name = customTypeName;
|
||||
}
|
||||
|
||||
return new CustomTypeSyntax(GetTokens(startIndex), module, name.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.Caret))
|
||||
{
|
||||
var baseType = ParseType();
|
||||
return new PointerTypeSyntax(GetTokens(startIndex), baseType);
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.Func))
|
||||
{
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
|
||||
List<TypeSyntax> parameters = [];
|
||||
while (!TryExpectSymbol(Symbol.CloseParen))
|
||||
{
|
||||
parameters.Add(ParseType());
|
||||
if (!TryExpectSymbol(Symbol.Comma))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var returnType = TryExpectSymbol(Symbol.Colon)
|
||||
? ParseType()
|
||||
: new VoidTypeSyntax([]);
|
||||
|
||||
return new FuncTypeSyntax(GetTokens(startIndex), parameters, returnType);
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.OpenBracket))
|
||||
{
|
||||
if (TryExpectIntLiteral(out var intLiteral))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseBracket);
|
||||
var baseType = ParseType();
|
||||
return new ConstArrayTypeSyntax(GetTokens(startIndex), baseType, Convert.ToInt64(intLiteral.Value, intLiteral.Base));
|
||||
}
|
||||
else if (TryExpectSymbol(Symbol.QuestionMark))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseBracket);
|
||||
var baseType = ParseType();
|
||||
return new ArrayTypeSyntax(GetTokens(startIndex), baseType);
|
||||
}
|
||||
else
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseBracket);
|
||||
var baseType = ParseType();
|
||||
return new SliceTypeSyntax(GetTokens(startIndex), baseType);
|
||||
}
|
||||
}
|
||||
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Invalid type syntax")
|
||||
.WithHelp("Expected type name, '^' for pointer, or '[]' for array")
|
||||
.At(CurrentToken)
|
||||
.Build());
|
||||
}
|
||||
|
||||
private Token ExpectToken()
|
||||
{
|
||||
if (!HasToken)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error("Unexpected end of file")
|
||||
.WithHelp("Expected more tokens to complete the syntax")
|
||||
.At(_tokens[^1])
|
||||
.Build());
|
||||
}
|
||||
|
||||
var token = CurrentToken!;
|
||||
Next();
|
||||
return token;
|
||||
}
|
||||
|
||||
private SymbolToken ExpectSymbol()
|
||||
{
|
||||
var token = ExpectToken();
|
||||
if (token is not SymbolToken symbol)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error($"Expected symbol, but found {token.GetType().Name}")
|
||||
.WithHelp("This position requires a symbol like '(', ')', '{', '}', etc.")
|
||||
.At(token)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return symbol;
|
||||
}
|
||||
|
||||
private void ExpectSymbol(Symbol expectedSymbol)
|
||||
{
|
||||
var token = ExpectSymbol();
|
||||
if (token.Symbol != expectedSymbol)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error($"Expected '{expectedSymbol}', but found '{token.Symbol}'")
|
||||
.WithHelp($"Insert '{expectedSymbol}' here")
|
||||
.At(token)
|
||||
.Build());
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryExpectSymbol(out Symbol symbol)
|
||||
{
|
||||
if (CurrentToken is SymbolToken symbolToken)
|
||||
{
|
||||
Next();
|
||||
symbol = symbolToken.Symbol;
|
||||
return true;
|
||||
}
|
||||
|
||||
symbol = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryExpectSymbol(Symbol symbol)
|
||||
{
|
||||
if (CurrentToken is SymbolToken symbolToken && symbolToken.Symbol == symbol)
|
||||
{
|
||||
Next();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TryExpectIdentifier([NotNullWhen(true)] out IdentifierToken? identifier)
|
||||
{
|
||||
if (CurrentToken is IdentifierToken identifierToken)
|
||||
{
|
||||
identifier = identifierToken;
|
||||
Next();
|
||||
return true;
|
||||
}
|
||||
|
||||
identifier = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private IdentifierToken ExpectIdentifier()
|
||||
{
|
||||
var token = ExpectToken();
|
||||
if (token is not IdentifierToken identifier)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error($"Expected identifier, but found {token.GetType().Name}")
|
||||
.WithHelp("Provide a valid identifier name here")
|
||||
.At(token)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return identifier;
|
||||
}
|
||||
|
||||
private bool TryExpectIntLiteral([NotNullWhen(true)] out IntLiteralToken? stringLiteral)
|
||||
{
|
||||
if (CurrentToken is IntLiteralToken token)
|
||||
{
|
||||
stringLiteral = token;
|
||||
Next();
|
||||
return true;
|
||||
}
|
||||
|
||||
stringLiteral = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private StringLiteralToken ExpectStringLiteral()
|
||||
{
|
||||
var token = ExpectToken();
|
||||
if (token is not StringLiteralToken identifier)
|
||||
{
|
||||
throw new ParseException(Diagnostic
|
||||
.Error($"Expected string literal, but found {token.GetType().Name}")
|
||||
.WithHelp("Provide a valid string literal")
|
||||
.At(token)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return identifier;
|
||||
}
|
||||
|
||||
private void Next()
|
||||
{
|
||||
_tokenIndex++;
|
||||
}
|
||||
|
||||
private List<Token> GetTokens(int tokenStartIndex)
|
||||
{
|
||||
return _tokens.Skip(tokenStartIndex).Take(_tokenIndex - tokenStartIndex).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public record SyntaxTree(List<DefinitionSyntax> Definitions, string ModuleName, List<string> Imports);
|
||||
|
||||
public class ParseException : Exception
|
||||
{
|
||||
public Diagnostic Diagnostic { get; }
|
||||
|
||||
public ParseException(Diagnostic diagnostic) : base(diagnostic.Message)
|
||||
{
|
||||
Diagnostic = diagnostic;
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
namespace NubLang.Syntax;
|
||||
|
||||
public abstract record SyntaxNode(List<Token> Tokens);
|
||||
|
||||
#region Definitions
|
||||
|
||||
public abstract record DefinitionSyntax(List<Token> Tokens, string Name, bool Exported) : SyntaxNode(Tokens);
|
||||
|
||||
public record FuncParameterSyntax(List<Token> Tokens, string Name, TypeSyntax Type) : SyntaxNode(Tokens);
|
||||
|
||||
public record FuncPrototypeSyntax(List<Token> Tokens, string Name, bool Exported, string? ExternSymbol, List<FuncParameterSyntax> Parameters, TypeSyntax ReturnType) : SyntaxNode(Tokens);
|
||||
|
||||
public record FuncSyntax(List<Token> Tokens, FuncPrototypeSyntax Prototype, BlockSyntax? Body) : DefinitionSyntax(Tokens, Prototype.Name, Prototype.Exported);
|
||||
|
||||
public record StructFieldSyntax(List<Token> Tokens, string Name, TypeSyntax Type, ExpressionSyntax? Value) : SyntaxNode(Tokens);
|
||||
|
||||
public record StructSyntax(List<Token> Tokens, string Name, bool Exported, List<StructFieldSyntax> Fields) : DefinitionSyntax(Tokens, Name, Exported);
|
||||
|
||||
public record EnumFieldSyntax(List<Token> Tokens, string Name, long Value) : SyntaxNode(Tokens);
|
||||
|
||||
public record EnumSyntax(List<Token> Tokens, string Name, bool Exported, TypeSyntax? Type, List<EnumFieldSyntax> Fields) : DefinitionSyntax(Tokens, Name, Exported);
|
||||
|
||||
public enum UnaryOperatorSyntax
|
||||
{
|
||||
Negate,
|
||||
Invert
|
||||
}
|
||||
|
||||
public enum BinaryOperatorSyntax
|
||||
{
|
||||
Equal,
|
||||
NotEqual,
|
||||
GreaterThan,
|
||||
GreaterThanOrEqual,
|
||||
LessThan,
|
||||
LessThanOrEqual,
|
||||
LogicalAnd,
|
||||
LogicalOr,
|
||||
Plus,
|
||||
Minus,
|
||||
Multiply,
|
||||
Divide,
|
||||
Modulo,
|
||||
LeftShift,
|
||||
RightShift,
|
||||
BitwiseAnd,
|
||||
BitwiseXor,
|
||||
BitwiseOr,
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Statements
|
||||
|
||||
public abstract record StatementSyntax(List<Token> Tokens) : SyntaxNode(Tokens);
|
||||
|
||||
public record BlockSyntax(List<Token> Tokens, List<StatementSyntax> Statements) : StatementSyntax(Tokens);
|
||||
|
||||
public record StatementExpressionSyntax(List<Token> Tokens, ExpressionSyntax Expression) : StatementSyntax(Tokens);
|
||||
|
||||
public record ReturnSyntax(List<Token> Tokens, ExpressionSyntax? Value) : StatementSyntax(Tokens);
|
||||
|
||||
public record AssignmentSyntax(List<Token> Tokens, ExpressionSyntax Target, ExpressionSyntax Value) : StatementSyntax(Tokens);
|
||||
|
||||
public record IfSyntax(List<Token> Tokens, ExpressionSyntax Condition, BlockSyntax Body, Variant<IfSyntax, BlockSyntax>? Else) : StatementSyntax(Tokens);
|
||||
|
||||
public record VariableDeclarationSyntax(List<Token> Tokens, string Name, TypeSyntax? ExplicitType, ExpressionSyntax? Assignment) : StatementSyntax(Tokens);
|
||||
|
||||
public record ContinueSyntax(List<Token> Tokens) : StatementSyntax(Tokens);
|
||||
|
||||
public record BreakSyntax(List<Token> Tokens) : StatementSyntax(Tokens);
|
||||
|
||||
public record DeferSyntax(List<Token> Tokens, StatementSyntax Statement) : StatementSyntax(Tokens);
|
||||
|
||||
public record WhileSyntax(List<Token> Tokens, ExpressionSyntax Condition, BlockSyntax Body) : StatementSyntax(Tokens);
|
||||
|
||||
public record ForSyntax(List<Token> Tokens, string ElementName, string? IndexName, ExpressionSyntax Target, BlockSyntax Body) : StatementSyntax(Tokens);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Expressions
|
||||
|
||||
public abstract record ExpressionSyntax(List<Token> Tokens) : SyntaxNode(Tokens);
|
||||
|
||||
public record BinaryExpressionSyntax(List<Token> Tokens, ExpressionSyntax Left, BinaryOperatorSyntax Operator, ExpressionSyntax Right) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record UnaryExpressionSyntax(List<Token> Tokens, UnaryOperatorSyntax Operator, ExpressionSyntax Operand) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record FuncCallSyntax(List<Token> Tokens, ExpressionSyntax Expression, List<ExpressionSyntax> Parameters) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record LocalIdentifierSyntax(List<Token> Tokens, string Name) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record ModuleIdentifierSyntax(List<Token> Tokens, string Module, string Name) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record ArrayInitializerSyntax(List<Token> Tokens, List<ExpressionSyntax> Values) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record ArrayIndexAccessSyntax(List<Token> Tokens, ExpressionSyntax Target, ExpressionSyntax Index) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record AddressOfSyntax(List<Token> Tokens, ExpressionSyntax Target) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record IntLiteralSyntax(List<Token> Tokens, string Value, int Base) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record StringLiteralSyntax(List<Token> Tokens, string Value) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record BoolLiteralSyntax(List<Token> Tokens, bool Value) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record FloatLiteralSyntax(List<Token> Tokens, string Value) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record MemberAccessSyntax(List<Token> Tokens, ExpressionSyntax Target, string Member) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record StructInitializerSyntax(List<Token> Tokens, TypeSyntax? StructType, Dictionary<string, ExpressionSyntax> Initializers) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record DereferenceSyntax(List<Token> Tokens, ExpressionSyntax Target) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record SizeBuiltinSyntax(List<Token> Tokens, TypeSyntax Type) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record InterpretBuiltinSyntax(List<Token> Tokens, TypeSyntax Type, ExpressionSyntax Target) : ExpressionSyntax(Tokens);
|
||||
|
||||
public record FloatToIntBuiltinSyntax(List<Token> Tokens, TypeSyntax Type, ExpressionSyntax Value) : ExpressionSyntax(Tokens);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Types
|
||||
|
||||
public abstract record TypeSyntax(List<Token> Tokens) : SyntaxNode(Tokens);
|
||||
|
||||
public record FuncTypeSyntax(List<Token> Tokens, List<TypeSyntax> Parameters, TypeSyntax ReturnType) : TypeSyntax(Tokens);
|
||||
|
||||
public record PointerTypeSyntax(List<Token> Tokens, TypeSyntax BaseType) : TypeSyntax(Tokens);
|
||||
|
||||
public record VoidTypeSyntax(List<Token> Tokens) : TypeSyntax(Tokens);
|
||||
|
||||
public record IntTypeSyntax(List<Token> Tokens, bool Signed, int Width) : TypeSyntax(Tokens);
|
||||
|
||||
public record FloatTypeSyntax(List<Token> Tokens, int Width) : TypeSyntax(Tokens);
|
||||
|
||||
public record BoolTypeSyntax(List<Token> Tokens) : TypeSyntax(Tokens);
|
||||
|
||||
public record StringTypeSyntax(List<Token> Tokens) : TypeSyntax(Tokens);
|
||||
|
||||
public record CStringTypeSyntax(List<Token> Tokens) : TypeSyntax(Tokens);
|
||||
|
||||
public record SliceTypeSyntax(List<Token> Tokens, TypeSyntax BaseType) : TypeSyntax(Tokens);
|
||||
|
||||
public record ArrayTypeSyntax(List<Token> Tokens, TypeSyntax BaseType) : TypeSyntax(Tokens);
|
||||
|
||||
public record ConstArrayTypeSyntax(List<Token> Tokens, TypeSyntax BaseType, long Size) : TypeSyntax(Tokens);
|
||||
|
||||
public record CustomTypeSyntax(List<Token> Tokens, string? Module, string Name) : TypeSyntax(Tokens);
|
||||
|
||||
#endregion
|
||||
@@ -1,77 +0,0 @@
|
||||
using NubLang.Diagnostics;
|
||||
|
||||
namespace NubLang.Syntax;
|
||||
|
||||
public enum Symbol
|
||||
{
|
||||
// Control
|
||||
If,
|
||||
Else,
|
||||
While,
|
||||
For,
|
||||
In,
|
||||
Break,
|
||||
Continue,
|
||||
Return,
|
||||
Let,
|
||||
Defer,
|
||||
|
||||
// Declaration
|
||||
Func,
|
||||
Struct,
|
||||
Enum,
|
||||
Import,
|
||||
Module,
|
||||
|
||||
// Modifier
|
||||
Extern,
|
||||
Export,
|
||||
|
||||
Colon,
|
||||
DoubleColon,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
OpenBrace,
|
||||
CloseBrace,
|
||||
OpenBracket,
|
||||
CloseBracket,
|
||||
Comma,
|
||||
Period,
|
||||
Assign,
|
||||
Bang,
|
||||
Equal,
|
||||
NotEqual,
|
||||
LessThan,
|
||||
LessThanOrEqual,
|
||||
GreaterThan,
|
||||
GreaterThanOrEqual,
|
||||
Plus,
|
||||
Minus,
|
||||
Star,
|
||||
ForwardSlash,
|
||||
Caret,
|
||||
Ampersand,
|
||||
Semi,
|
||||
Percent,
|
||||
LeftShift,
|
||||
RightShift,
|
||||
Pipe,
|
||||
And,
|
||||
Or,
|
||||
At,
|
||||
QuestionMark,
|
||||
}
|
||||
|
||||
public abstract record Token(SourceSpan Span);
|
||||
|
||||
public record IdentifierToken(SourceSpan Span, string Value) : Token(Span);
|
||||
|
||||
public record IntLiteralToken(SourceSpan Span, string Value, int Base) : Token(Span);
|
||||
|
||||
public record StringLiteralToken(SourceSpan Span, string Value) : Token(Span);
|
||||
|
||||
public record BoolLiteralToken(SourceSpan Span, bool Value) : Token(Span);
|
||||
|
||||
public record FloatLiteralToken(SourceSpan Span, string Value) : Token(Span);
|
||||
|
||||
public record SymbolToken(SourceSpan Span, Symbol Symbol) : Token(Span);
|
||||
@@ -1,331 +0,0 @@
|
||||
using NubLang.Diagnostics;
|
||||
|
||||
namespace NubLang.Syntax;
|
||||
|
||||
public sealed class Tokenizer
|
||||
{
|
||||
private static readonly Dictionary<string, Symbol> Keywords = new()
|
||||
{
|
||||
["func"] = Symbol.Func,
|
||||
["if"] = Symbol.If,
|
||||
["else"] = Symbol.Else,
|
||||
["while"] = Symbol.While,
|
||||
["for"] = Symbol.For,
|
||||
["in"] = Symbol.In,
|
||||
["break"] = Symbol.Break,
|
||||
["continue"] = Symbol.Continue,
|
||||
["return"] = Symbol.Return,
|
||||
["struct"] = Symbol.Struct,
|
||||
["let"] = Symbol.Let,
|
||||
["extern"] = Symbol.Extern,
|
||||
["module"] = Symbol.Module,
|
||||
["export"] = Symbol.Export,
|
||||
["import"] = Symbol.Import,
|
||||
["defer"] = Symbol.Defer,
|
||||
["enum"] = Symbol.Enum,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<char[], Symbol> Symbols = new()
|
||||
{
|
||||
[['=', '=']] = Symbol.Equal,
|
||||
[['!', '=']] = Symbol.NotEqual,
|
||||
[['<', '=']] = Symbol.LessThanOrEqual,
|
||||
[['>', '=']] = Symbol.GreaterThanOrEqual,
|
||||
[['<', '<']] = Symbol.LeftShift,
|
||||
[['>', '>']] = Symbol.RightShift,
|
||||
[['&', '&']] = Symbol.And,
|
||||
[['|', '|']] = Symbol.Or,
|
||||
[[':', ':']] = Symbol.DoubleColon,
|
||||
[[':']] = Symbol.Colon,
|
||||
[['(']] = Symbol.OpenParen,
|
||||
[[')']] = Symbol.CloseParen,
|
||||
[['{']] = Symbol.OpenBrace,
|
||||
[['}']] = Symbol.CloseBrace,
|
||||
[['[']] = Symbol.OpenBracket,
|
||||
[[']']] = Symbol.CloseBracket,
|
||||
[[',']] = Symbol.Comma,
|
||||
[['.']] = Symbol.Period,
|
||||
[['=']] = Symbol.Assign,
|
||||
[['<']] = Symbol.LessThan,
|
||||
[['>']] = Symbol.GreaterThan,
|
||||
[['+']] = Symbol.Plus,
|
||||
[['-']] = Symbol.Minus,
|
||||
[['*']] = Symbol.Star,
|
||||
[['/']] = Symbol.ForwardSlash,
|
||||
[['!']] = Symbol.Bang,
|
||||
[['^']] = Symbol.Caret,
|
||||
[['&']] = Symbol.Ampersand,
|
||||
[[';']] = Symbol.Semi,
|
||||
[['%']] = Symbol.Percent,
|
||||
[['|']] = Symbol.Pipe,
|
||||
[['@']] = Symbol.At,
|
||||
[['?']] = Symbol.QuestionMark,
|
||||
};
|
||||
|
||||
private static readonly (char[] Pattern, Symbol Symbol)[] OrderedSymbols = Symbols
|
||||
.OrderByDescending(kvp => kvp.Key.Length)
|
||||
.Select(kvp => (kvp.Key, kvp.Value))
|
||||
.ToArray();
|
||||
|
||||
private readonly string _fileName;
|
||||
private readonly string _content;
|
||||
private int _index = 0;
|
||||
private int _line = 1;
|
||||
private int _column = 1;
|
||||
|
||||
public Tokenizer(string fileName, string content)
|
||||
{
|
||||
_fileName = fileName;
|
||||
_content = content;
|
||||
}
|
||||
|
||||
public List<Diagnostic> Diagnostics { get; } = [];
|
||||
public List<Token> Tokens { get; } = [];
|
||||
|
||||
public void Tokenize()
|
||||
{
|
||||
Diagnostics.Clear();
|
||||
Tokens.Clear();
|
||||
_index = 0;
|
||||
_line = 1;
|
||||
_column = 1;
|
||||
|
||||
while (Peek().HasValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var current = Peek()!.Value;
|
||||
if (char.IsWhiteSpace(current))
|
||||
{
|
||||
if (current is '\n')
|
||||
{
|
||||
_line += 1;
|
||||
// note(nub31): Next increments the column, so 0 is correct here
|
||||
_column = 0;
|
||||
}
|
||||
|
||||
Next();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current == '/' && Peek(1) == '/')
|
||||
{
|
||||
// note(nub31): Keep newline so next iteration increments the line counter
|
||||
while (Peek() is not '\n')
|
||||
{
|
||||
Next();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
Tokens.Add(ParseToken(current, _line, _column));
|
||||
}
|
||||
catch (TokenizerException e)
|
||||
{
|
||||
Diagnostics.Add(e.Diagnostic);
|
||||
Next();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Token ParseToken(char current, int lineStart, int columnStart)
|
||||
{
|
||||
if (char.IsLetter(current) || current == '_')
|
||||
{
|
||||
var buffer = string.Empty;
|
||||
|
||||
while (Peek() != null && (char.IsLetterOrDigit(Peek()!.Value) || Peek() == '_'))
|
||||
{
|
||||
buffer += Peek();
|
||||
Next();
|
||||
}
|
||||
|
||||
if (Keywords.TryGetValue(buffer, out var keywordSymbol))
|
||||
{
|
||||
return new SymbolToken(CreateSpan(lineStart, columnStart), keywordSymbol);
|
||||
}
|
||||
|
||||
if (buffer is "true" or "false")
|
||||
{
|
||||
return new BoolLiteralToken(CreateSpan(lineStart, columnStart), Convert.ToBoolean(buffer));
|
||||
}
|
||||
|
||||
return new IdentifierToken(CreateSpan(lineStart, columnStart), buffer);
|
||||
}
|
||||
|
||||
if (char.IsDigit(current))
|
||||
{
|
||||
var buffer = string.Empty;
|
||||
|
||||
if (current == '0' && Peek(1) is 'x')
|
||||
{
|
||||
buffer += "0x";
|
||||
Next();
|
||||
Next();
|
||||
while (Peek() != null && Uri.IsHexDigit(Peek()!.Value))
|
||||
{
|
||||
buffer += Peek()!.Value;
|
||||
Next();
|
||||
}
|
||||
|
||||
if (buffer.Length <= 2)
|
||||
{
|
||||
throw new TokenizerException(Diagnostic
|
||||
.Error("Invalid hex literal, no digits found")
|
||||
.At(_fileName, _line, _column)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return new IntLiteralToken(CreateSpan(lineStart, columnStart), buffer, 16);
|
||||
}
|
||||
|
||||
if (current == '0' && Peek(1) is 'b')
|
||||
{
|
||||
buffer += "0b";
|
||||
Next();
|
||||
Next();
|
||||
while (Peek() != null && (Peek() == '0' || Peek() == '1'))
|
||||
{
|
||||
buffer += Peek()!.Value;
|
||||
Next();
|
||||
}
|
||||
|
||||
if (buffer.Length <= 2)
|
||||
{
|
||||
throw new TokenizerException(Diagnostic
|
||||
.Error("Invalid binary literal, no digits found")
|
||||
.At(_fileName, _line, _column)
|
||||
.Build());
|
||||
}
|
||||
|
||||
return new IntLiteralToken(CreateSpan(lineStart, columnStart), buffer, 2);
|
||||
}
|
||||
|
||||
var isFloat = false;
|
||||
while (Peek() != null)
|
||||
{
|
||||
var next = Peek()!.Value;
|
||||
if (next == '.')
|
||||
{
|
||||
if (isFloat)
|
||||
{
|
||||
throw new TokenizerException(Diagnostic
|
||||
.Error("More than one period found in float literal")
|
||||
.At(_fileName, _line, _column)
|
||||
.Build());
|
||||
}
|
||||
|
||||
isFloat = true;
|
||||
buffer += next;
|
||||
Next();
|
||||
}
|
||||
else if (char.IsDigit(next))
|
||||
{
|
||||
buffer += next;
|
||||
Next();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isFloat)
|
||||
{
|
||||
return new FloatLiteralToken(CreateSpan(lineStart, columnStart), buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new IntLiteralToken(CreateSpan(lineStart, columnStart), buffer, 10);
|
||||
}
|
||||
}
|
||||
|
||||
if (current == '"')
|
||||
{
|
||||
Next();
|
||||
var buffer = string.Empty;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var next = Peek();
|
||||
if (!next.HasValue)
|
||||
{
|
||||
throw new TokenizerException(Diagnostic
|
||||
.Error("Unclosed string literal")
|
||||
.At(_fileName, _line, _column)
|
||||
.Build());
|
||||
}
|
||||
|
||||
if (next is '\n')
|
||||
{
|
||||
_line += 1;
|
||||
break;
|
||||
}
|
||||
|
||||
if (next is '"')
|
||||
{
|
||||
Next();
|
||||
break;
|
||||
}
|
||||
|
||||
buffer += next;
|
||||
Next();
|
||||
}
|
||||
|
||||
return new StringLiteralToken(CreateSpan(lineStart, columnStart), buffer);
|
||||
}
|
||||
|
||||
foreach (var (pattern, symbol) in OrderedSymbols)
|
||||
{
|
||||
for (var i = 0; i < pattern.Length; i++)
|
||||
{
|
||||
var c = Peek(i);
|
||||
if (!c.HasValue || c.Value != pattern[i]) break;
|
||||
|
||||
if (i == pattern.Length - 1)
|
||||
{
|
||||
for (var j = 0; j <= i; j++)
|
||||
{
|
||||
Next();
|
||||
}
|
||||
|
||||
return new SymbolToken(CreateSpan(lineStart, columnStart), symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new TokenizerException(Diagnostic.Error($"Unknown token '{current}'").Build());
|
||||
}
|
||||
|
||||
private SourceSpan CreateSpan(int lineStart, int columnStart)
|
||||
{
|
||||
return new SourceSpan(_fileName, new SourceLocation(lineStart, columnStart), new SourceLocation(_line, _column));
|
||||
}
|
||||
|
||||
private char? Peek(int offset = 0)
|
||||
{
|
||||
if (_index + offset < _content.Length)
|
||||
{
|
||||
return _content[_index + offset];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Next()
|
||||
{
|
||||
_index += 1;
|
||||
_column += 1;
|
||||
}
|
||||
}
|
||||
|
||||
public class TokenizerException : Exception
|
||||
{
|
||||
public Diagnostic Diagnostic { get; }
|
||||
|
||||
public TokenizerException(Diagnostic diagnostic) : base(diagnostic.Message)
|
||||
{
|
||||
Diagnostic = diagnostic;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace NubLang;
|
||||
|
||||
public readonly struct Variant<T1, T2> where T1 : notnull where T2 : notnull
|
||||
{
|
||||
public Variant()
|
||||
{
|
||||
throw new InvalidOperationException("Variant must be initialized with a value");
|
||||
}
|
||||
|
||||
public Variant(T1 value)
|
||||
{
|
||||
_value = value;
|
||||
}
|
||||
|
||||
public Variant(T2 value)
|
||||
{
|
||||
_value = value;
|
||||
}
|
||||
|
||||
private readonly object _value;
|
||||
|
||||
public void Match(Action<T1> on1, Action<T2> on2)
|
||||
{
|
||||
switch (_value)
|
||||
{
|
||||
case T1 v1:
|
||||
on1(v1);
|
||||
break;
|
||||
case T2 v2:
|
||||
on2(v2);
|
||||
break;
|
||||
default:
|
||||
throw new InvalidCastException();
|
||||
}
|
||||
}
|
||||
|
||||
public T Match<T>(Func<T1, T> on1, Func<T2, T> on2)
|
||||
{
|
||||
return _value switch
|
||||
{
|
||||
T1 v1 => on1(v1),
|
||||
T2 v2 => on2(v2),
|
||||
_ => throw new InvalidCastException()
|
||||
};
|
||||
}
|
||||
|
||||
public bool IsCase1([NotNullWhen(true)] out T1? value)
|
||||
{
|
||||
if (_value is T1 converted)
|
||||
{
|
||||
value = converted;
|
||||
return true;
|
||||
}
|
||||
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool IsCase2([NotNullWhen(true)] out T2? value)
|
||||
{
|
||||
if (_value is T2 converted)
|
||||
{
|
||||
value = converted;
|
||||
return true;
|
||||
}
|
||||
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static implicit operator Variant<T1, T2>(T1 value) => new(value);
|
||||
public static implicit operator Variant<T1, T2>(T2 value) => new(value);
|
||||
}
|
||||
110
compiler/NubLib.cs
Normal file
110
compiler/NubLib.cs
Normal file
@@ -0,0 +1,110 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
public class NubLib
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
};
|
||||
|
||||
public static void Pack(string outputPath, string archivePath, Manifest manifest)
|
||||
{
|
||||
using var fs = new FileStream(outputPath, FileMode.Create);
|
||||
using var zip = new ZipArchive(fs, ZipArchiveMode.Create);
|
||||
|
||||
var manifestEntry = zip.CreateEntry("manifest.json");
|
||||
using (var writer = new StreamWriter(manifestEntry.Open()))
|
||||
{
|
||||
var serialized = JsonSerializer.Serialize(manifest, JsonOptions);
|
||||
|
||||
writer.Write(serialized);
|
||||
}
|
||||
|
||||
var archiveEntry = zip.CreateEntry("lib.a");
|
||||
|
||||
using var entryStream = archiveEntry.Open();
|
||||
using var fileStream = File.OpenRead(archivePath);
|
||||
|
||||
fileStream.CopyTo(entryStream);
|
||||
}
|
||||
|
||||
public static NubLibLoadResult Unpack(string nublibPath)
|
||||
{
|
||||
using var fs = new FileStream(nublibPath, FileMode.Open, FileAccess.Read);
|
||||
using var zip = new ZipArchive(fs, ZipArchiveMode.Read);
|
||||
|
||||
var manifestEntry = zip.GetEntry("manifest.json") ?? throw new FileNotFoundException("Manifest not found in nublib", "manifest.json");
|
||||
|
||||
Manifest manifest;
|
||||
using (var reader = new StreamReader(manifestEntry.Open()))
|
||||
{
|
||||
var json = reader.ReadToEnd();
|
||||
manifest = JsonSerializer.Deserialize<Manifest>(json, JsonOptions) ?? throw new InvalidDataException("Failed to deserialize manifest.json");
|
||||
}
|
||||
|
||||
var archiveEntry = zip.Entries.FirstOrDefault(e => e.Name.EndsWith(".a")) ?? throw new FileNotFoundException("Archive not found in nublib", "*.a");
|
||||
|
||||
string tempArchivePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".a");
|
||||
using (var entryStream = archiveEntry.Open())
|
||||
using (var tempFile = File.Create(tempArchivePath))
|
||||
{
|
||||
entryStream.CopyTo(tempFile);
|
||||
}
|
||||
|
||||
return new NubLibLoadResult(manifest, tempArchivePath);
|
||||
}
|
||||
|
||||
public record NubLibLoadResult(Manifest Manifest, string ArchivePath);
|
||||
}
|
||||
|
||||
public record Manifest(Dictionary<string, Manifest.Module> Modules)
|
||||
{
|
||||
public static Manifest Create(ModuleGraph moduleGraph)
|
||||
{
|
||||
var modules = new Dictionary<string, Module>();
|
||||
|
||||
foreach (var module in moduleGraph.GetModules())
|
||||
{
|
||||
var types = module.GetTypes().ToDictionary(x => x.Key, x => ConvertType(x.Value));
|
||||
var identifiers = module.GetIdentifiers().ToDictionary(x => x.Key, x => new Module.IdentifierInfo(x.Value.Type, x.Value.Exported, x.Value.Extern, x.Value.MangledName));
|
||||
modules[module.Name] = new Module(types, identifiers);
|
||||
}
|
||||
|
||||
return new Manifest(modules);
|
||||
|
||||
static Module.TypeInfo ConvertType(Compiler.Module.TypeInfo typeInfo)
|
||||
{
|
||||
return typeInfo switch
|
||||
{
|
||||
Compiler.Module.TypeInfoStruct s => new Module.TypeInfoStruct(s.Exported, s.Packed, s.Fields.Select(x => new Module.TypeInfoStruct.Field(x.Name, x.Type)).ToList()),
|
||||
Compiler.Module.TypeInfoEnum e => new Module.TypeInfoEnum(e.Exported, e.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name, v.Type)).ToList()),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record Module(Dictionary<string, Module.TypeInfo> Types, Dictionary<string, Module.IdentifierInfo> Identifiers)
|
||||
{
|
||||
public record IdentifierInfo(NubType Type, bool Exported, bool Extern, string MangledName);
|
||||
|
||||
[JsonDerivedType(typeof(TypeInfoStruct), "struct")]
|
||||
[JsonDerivedType(typeof(TypeInfoEnum), "enum")]
|
||||
public abstract record TypeInfo(bool Exported);
|
||||
|
||||
public record TypeInfoStruct(bool Exported, bool Packed, IReadOnlyList<TypeInfoStruct.Field> Fields) : TypeInfo(Exported)
|
||||
{
|
||||
public record Field(string Name, NubType Type);
|
||||
}
|
||||
|
||||
public record TypeInfoEnum(bool Exported, IReadOnlyList<TypeInfoEnum.Variant> Variants) : TypeInfo(Exported)
|
||||
{
|
||||
public record Variant(string Name, NubType? Type);
|
||||
}
|
||||
}
|
||||
}
|
||||
708
compiler/NubType.cs
Normal file
708
compiler/NubType.cs
Normal file
@@ -0,0 +1,708 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
[JsonConverter(typeof(NubTypeJsonConverter))]
|
||||
public abstract class NubType
|
||||
{
|
||||
public abstract override string ToString();
|
||||
|
||||
[Obsolete("Use IsAssignableTo instead of ==", error: true)]
|
||||
public static bool operator ==(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo");
|
||||
|
||||
[Obsolete("Use IsAssignableTo instead of ==", error: true)]
|
||||
public static bool operator !=(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo");
|
||||
|
||||
public bool IsAssignableTo(NubType target)
|
||||
{
|
||||
return (this, target) switch
|
||||
{
|
||||
(NubTypeEnumVariant variant, NubTypeEnum targetEnum) => ReferenceEquals(variant.EnumType, targetEnum),
|
||||
_ => ReferenceEquals(this, target),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class NubTypeVoid : NubType
|
||||
{
|
||||
public static readonly NubTypeVoid Instance = new();
|
||||
|
||||
private NubTypeVoid()
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => "void";
|
||||
}
|
||||
|
||||
public class NubTypeUInt : NubType
|
||||
{
|
||||
private static readonly Dictionary<int, NubTypeUInt> Cache = new();
|
||||
|
||||
public static NubTypeUInt Get(int width)
|
||||
{
|
||||
if (!Cache.TryGetValue(width, out var type))
|
||||
Cache[width] = type = new NubTypeUInt(width);
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
private NubTypeUInt(int width)
|
||||
{
|
||||
Width = width;
|
||||
}
|
||||
|
||||
public override string ToString() => $"u{Width}";
|
||||
}
|
||||
|
||||
public class NubTypeSInt : NubType
|
||||
{
|
||||
private static readonly Dictionary<int, NubTypeSInt> Cache = new();
|
||||
|
||||
public static NubTypeSInt Get(int width)
|
||||
{
|
||||
if (!Cache.TryGetValue(width, out var type))
|
||||
Cache[width] = type = new NubTypeSInt(width);
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
private NubTypeSInt(int width)
|
||||
{
|
||||
Width = width;
|
||||
}
|
||||
|
||||
public override string ToString() => $"i{Width}";
|
||||
}
|
||||
|
||||
public class NubTypeBool : NubType
|
||||
{
|
||||
public static readonly NubTypeBool Instance = new();
|
||||
|
||||
private NubTypeBool()
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => "bool";
|
||||
}
|
||||
|
||||
public class NubTypeString : NubType
|
||||
{
|
||||
public static readonly NubTypeString Instance = new();
|
||||
|
||||
private NubTypeString()
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => "string";
|
||||
}
|
||||
|
||||
public class NubTypeChar : NubType
|
||||
{
|
||||
public static readonly NubTypeChar Instance = new();
|
||||
|
||||
private NubTypeChar()
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => "char";
|
||||
}
|
||||
|
||||
public class NubTypeStruct : NubType
|
||||
{
|
||||
private static readonly Dictionary<(string Module, string Name), NubTypeStruct> Cache = new();
|
||||
|
||||
public static NubTypeStruct Get(string module, string name)
|
||||
{
|
||||
if (!Cache.TryGetValue((module, name), out var structType))
|
||||
Cache[(module, name)] = structType = new NubTypeStruct(module, name);
|
||||
|
||||
return structType;
|
||||
}
|
||||
|
||||
private NubTypeStruct(string module, string name)
|
||||
{
|
||||
Module = module;
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Module { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public override string ToString() => $"{Module}::{Name}";
|
||||
}
|
||||
|
||||
public class NubTypeAnonymousStruct : NubType
|
||||
{
|
||||
private static readonly Dictionary<Signature, NubTypeAnonymousStruct> Cache = new();
|
||||
|
||||
public static NubTypeAnonymousStruct Get(List<Field> fields)
|
||||
{
|
||||
var sig = new Signature(fields);
|
||||
|
||||
if (!Cache.TryGetValue(sig, out var func))
|
||||
Cache[sig] = func = new NubTypeAnonymousStruct(fields);
|
||||
|
||||
return func;
|
||||
}
|
||||
|
||||
private NubTypeAnonymousStruct(IReadOnlyList<Field> fields)
|
||||
{
|
||||
Fields = fields;
|
||||
}
|
||||
|
||||
public IReadOnlyList<Field> Fields { get; }
|
||||
|
||||
public override string ToString() => $"{{ {string.Join(", ", Fields.Select(x => $"{x.Name}: {x.Type}"))} }}";
|
||||
|
||||
public class Field(string name, NubType type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType Type { get; } = type;
|
||||
}
|
||||
|
||||
private record Signature(IReadOnlyList<Field> Fields);
|
||||
}
|
||||
|
||||
public class NubTypeEnum : NubType
|
||||
{
|
||||
private static readonly Dictionary<(string Module, string Name), NubTypeEnum> Cache = new();
|
||||
|
||||
public static NubTypeEnum Get(string module, string name)
|
||||
{
|
||||
if (!Cache.TryGetValue((module, name), out var enumType))
|
||||
Cache[(module, name)] = enumType = new NubTypeEnum(module, name);
|
||||
|
||||
return enumType;
|
||||
}
|
||||
|
||||
private NubTypeEnum(string module, string name)
|
||||
{
|
||||
Module = module;
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Module { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public override string ToString() => $"{Module}::{Name}";
|
||||
}
|
||||
|
||||
public class NubTypeEnumVariant : NubType
|
||||
{
|
||||
private static readonly Dictionary<(NubTypeEnum EnumType, string Variant), NubTypeEnumVariant> Cache = new();
|
||||
|
||||
public static NubTypeEnumVariant Get(NubTypeEnum enumType, string variant)
|
||||
{
|
||||
if (!Cache.TryGetValue((enumType, variant), out var variantType))
|
||||
Cache[(enumType, variant)] = variantType = new NubTypeEnumVariant(enumType, variant);
|
||||
|
||||
return variantType;
|
||||
}
|
||||
|
||||
private NubTypeEnumVariant(NubTypeEnum enumType, string variant)
|
||||
{
|
||||
EnumType = enumType;
|
||||
Variant = variant;
|
||||
}
|
||||
|
||||
public NubTypeEnum EnumType { get; }
|
||||
public string Variant { get; }
|
||||
|
||||
public override string ToString() => $"{EnumType}.{Variant}";
|
||||
}
|
||||
|
||||
public class NubTypePointer : NubType
|
||||
{
|
||||
private static readonly Dictionary<NubType, NubTypePointer> Cache = new();
|
||||
|
||||
public static NubTypePointer Get(NubType to)
|
||||
{
|
||||
if (!Cache.TryGetValue(to, out var ptr))
|
||||
Cache[to] = ptr = new NubTypePointer(to);
|
||||
|
||||
return ptr;
|
||||
}
|
||||
|
||||
public NubType To { get; }
|
||||
|
||||
private NubTypePointer(NubType to)
|
||||
{
|
||||
To = to;
|
||||
}
|
||||
|
||||
public override string ToString() => $"^{To}";
|
||||
}
|
||||
|
||||
public class NubTypeFunc : NubType
|
||||
{
|
||||
private static readonly Dictionary<Signature, NubTypeFunc> Cache = new();
|
||||
|
||||
public static NubTypeFunc Get(List<NubType> parameters, NubType returnType)
|
||||
{
|
||||
var sig = new Signature(parameters, returnType);
|
||||
|
||||
if (!Cache.TryGetValue(sig, out var func))
|
||||
Cache[sig] = func = new NubTypeFunc(parameters, returnType);
|
||||
|
||||
return func;
|
||||
}
|
||||
|
||||
public IReadOnlyList<NubType> Parameters { get; }
|
||||
public NubType ReturnType { get; }
|
||||
|
||||
private NubTypeFunc(List<NubType> parameters, NubType returnType)
|
||||
{
|
||||
Parameters = parameters;
|
||||
ReturnType = returnType;
|
||||
}
|
||||
|
||||
public override string ToString() => $"func({string.Join(' ', Parameters)}): {ReturnType}";
|
||||
|
||||
private record Signature(IReadOnlyList<NubType> Parameters, NubType ReturnType);
|
||||
}
|
||||
|
||||
public class NubTypeArray : NubType
|
||||
{
|
||||
private static readonly Dictionary<NubType, NubTypeArray> Cache = new();
|
||||
|
||||
public static NubTypeArray Get(NubType to)
|
||||
{
|
||||
if (!Cache.TryGetValue(to, out var ptr))
|
||||
Cache[to] = ptr = new NubTypeArray(to);
|
||||
|
||||
return ptr;
|
||||
}
|
||||
|
||||
public NubType ElementType { get; }
|
||||
|
||||
private NubTypeArray(NubType elementType)
|
||||
{
|
||||
ElementType = elementType;
|
||||
}
|
||||
|
||||
public override string ToString() => $"[]{ElementType}";
|
||||
}
|
||||
|
||||
public class TypeEncoder
|
||||
{
|
||||
public static string Encode(NubType type)
|
||||
{
|
||||
return new TypeEncoder().EncodeRoot(type);
|
||||
}
|
||||
|
||||
private TypeEncoder()
|
||||
{
|
||||
}
|
||||
|
||||
private string EncodeRoot(NubType type)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
EncodeType(sb, type);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private void EncodeType(StringBuilder sb, NubType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case NubTypeVoid:
|
||||
sb.Append('V');
|
||||
break;
|
||||
|
||||
case NubTypeBool:
|
||||
sb.Append('B');
|
||||
break;
|
||||
|
||||
case NubTypeUInt u:
|
||||
sb.Append($"U(");
|
||||
sb.Append(u.Width);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeSInt s:
|
||||
sb.Append($"I(");
|
||||
sb.Append(s.Width);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeString:
|
||||
sb.Append('S');
|
||||
break;
|
||||
|
||||
case NubTypeChar:
|
||||
sb.Append('C');
|
||||
break;
|
||||
|
||||
case NubTypePointer p:
|
||||
sb.Append("P(");
|
||||
EncodeType(sb, p.To);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeStruct st:
|
||||
sb.Append("TN(");
|
||||
sb.Append(st.Module);
|
||||
sb.Append(':');
|
||||
sb.Append(st.Name);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeEnum e:
|
||||
sb.Append("EN(");
|
||||
sb.Append(e.Module);
|
||||
sb.Append(':');
|
||||
sb.Append(e.Name);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeEnumVariant ev:
|
||||
sb.Append("EV(");
|
||||
sb.Append(ev.EnumType.Module);
|
||||
sb.Append(':');
|
||||
sb.Append(ev.EnumType.Name);
|
||||
sb.Append(':');
|
||||
sb.Append(ev.Variant);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeFunc fn:
|
||||
sb.Append("F(");
|
||||
for (int i = 0; i < fn.Parameters.Count; i++)
|
||||
{
|
||||
EncodeType(sb, fn.Parameters[i]);
|
||||
}
|
||||
EncodeType(sb, fn.ReturnType);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeAnonymousStruct s:
|
||||
sb.Append("TA(");
|
||||
foreach (var field in s.Fields)
|
||||
{
|
||||
sb.Append(field.Name);
|
||||
sb.Append(':');
|
||||
EncodeType(sb, field.Type);
|
||||
}
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeArray a:
|
||||
sb.Append("A(");
|
||||
EncodeType(sb, a.ElementType);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new NotSupportedException(type.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private class Definition(int index)
|
||||
{
|
||||
public int Index { get; } = index;
|
||||
public string? Encoded { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
public class TypeDecoder
|
||||
{
|
||||
public static NubType Decode(string encoded)
|
||||
{
|
||||
return new TypeDecoder(encoded).DecodeType();
|
||||
}
|
||||
|
||||
private TypeDecoder(string encoded)
|
||||
{
|
||||
this.encoded = encoded;
|
||||
}
|
||||
|
||||
private readonly string encoded;
|
||||
private int index = 0;
|
||||
|
||||
private NubType DecodeType()
|
||||
{
|
||||
var start = Consume();
|
||||
return start switch
|
||||
{
|
||||
'V' => NubTypeVoid.Instance,
|
||||
'B' => NubTypeBool.Instance,
|
||||
'U' => DecodeUInt(),
|
||||
'I' => DecodeSInt(),
|
||||
'S' => NubTypeString.Instance,
|
||||
'C' => NubTypeChar.Instance,
|
||||
'P' => DecodePointer(),
|
||||
'F' => DecodeFunc(),
|
||||
'T' => DecodeStruct(),
|
||||
'E' => DecodeEnum(),
|
||||
'A' => DecodeArray(),
|
||||
_ => throw new Exception($"'{start}' is not a valid start to a type")
|
||||
};
|
||||
}
|
||||
|
||||
private NubTypeUInt DecodeUInt()
|
||||
{
|
||||
Expect('(');
|
||||
var width = ExpectInt();
|
||||
Expect(')');
|
||||
return NubTypeUInt.Get(width);
|
||||
}
|
||||
|
||||
private NubTypeSInt DecodeSInt()
|
||||
{
|
||||
Expect('(');
|
||||
var width = ExpectInt();
|
||||
Expect(')');
|
||||
return NubTypeSInt.Get(width);
|
||||
}
|
||||
|
||||
private NubTypePointer DecodePointer()
|
||||
{
|
||||
Expect('(');
|
||||
var to = DecodeType();
|
||||
Expect(')');
|
||||
return NubTypePointer.Get(to);
|
||||
}
|
||||
|
||||
private NubTypeFunc DecodeFunc()
|
||||
{
|
||||
var types = new List<NubType>();
|
||||
|
||||
Expect('(');
|
||||
while (!TryExpect(')'))
|
||||
{
|
||||
types.Add(DecodeType());
|
||||
}
|
||||
|
||||
return NubTypeFunc.Get(types.Take(types.Count - 1).ToList(), types.Last());
|
||||
}
|
||||
|
||||
private NubType DecodeStruct()
|
||||
{
|
||||
|
||||
if (TryExpect('A'))
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
var fields = new List<NubTypeAnonymousStruct.Field>();
|
||||
|
||||
Expect('(');
|
||||
while (!TryExpect(')'))
|
||||
{
|
||||
while (!TryExpect(':'))
|
||||
{
|
||||
sb.Append(Consume());
|
||||
}
|
||||
|
||||
var name = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
var type = DecodeType();
|
||||
|
||||
fields.Add(new NubTypeAnonymousStruct.Field(name, type));
|
||||
}
|
||||
|
||||
return NubTypeAnonymousStruct.Get(fields);
|
||||
}
|
||||
|
||||
if (TryExpect('N'))
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
Expect('(');
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var module = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
while (!TryExpect(')'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var name = sb.ToString();
|
||||
|
||||
return NubTypeStruct.Get(module, name);
|
||||
}
|
||||
|
||||
throw new Exception("Expected 'A' or 'N'");
|
||||
}
|
||||
|
||||
private NubType DecodeEnum()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
if (TryExpect('V'))
|
||||
{
|
||||
Expect('(');
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var module = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var name = sb.ToString();
|
||||
|
||||
while (!TryExpect(')'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var variant = sb.ToString();
|
||||
|
||||
return NubTypeEnumVariant.Get(NubTypeEnum.Get(module, name), variant);
|
||||
}
|
||||
else if (TryExpect('N'))
|
||||
{
|
||||
Expect('(');
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var module = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
while (!TryExpect(')'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var name = sb.ToString();
|
||||
|
||||
return NubTypeEnum.Get(module, name);
|
||||
}
|
||||
|
||||
throw new Exception($"Expected 'V' or 'N'");
|
||||
}
|
||||
|
||||
private NubTypeArray DecodeArray()
|
||||
{
|
||||
Expect('(');
|
||||
var elementType = DecodeType();
|
||||
Expect(')');
|
||||
return NubTypeArray.Get(elementType);
|
||||
}
|
||||
|
||||
private bool TryPeek(out char c)
|
||||
{
|
||||
if (index >= encoded.Length)
|
||||
{
|
||||
c = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
c = encoded[index];
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryConsume(out char c)
|
||||
{
|
||||
if (index >= encoded.Length)
|
||||
{
|
||||
c = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
c = encoded[index];
|
||||
index += 1;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private char Consume()
|
||||
{
|
||||
if (!TryConsume(out var c))
|
||||
throw new Exception("Unexpected end of string");
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
private bool TryExpect(char c)
|
||||
{
|
||||
if (index >= encoded.Length)
|
||||
return false;
|
||||
|
||||
if (encoded[index] != c)
|
||||
return false;
|
||||
|
||||
Consume();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Expect(char c)
|
||||
{
|
||||
if (!TryExpect(c))
|
||||
throw new Exception($"Expected '{c}'");
|
||||
}
|
||||
|
||||
private int ExpectInt()
|
||||
{
|
||||
var buf = string.Empty;
|
||||
|
||||
while (TryPeek(out var c))
|
||||
{
|
||||
if (!char.IsDigit(c))
|
||||
break;
|
||||
|
||||
buf += Consume();
|
||||
}
|
||||
|
||||
return int.Parse(buf);
|
||||
}
|
||||
}
|
||||
|
||||
public class NubTypeJsonConverter : JsonConverter<NubType>
|
||||
{
|
||||
public override NubType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
return TypeDecoder.Decode(reader.GetString()!);
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, NubType value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStringValue(TypeEncoder.Encode(value));
|
||||
}
|
||||
}
|
||||
|
||||
public static class Hashing
|
||||
{
|
||||
public static ulong Fnv1a64(string text)
|
||||
{
|
||||
const ulong offset = 14695981039346656037UL;
|
||||
const ulong prime = 1099511628211UL;
|
||||
|
||||
ulong hash = offset;
|
||||
foreach (var c in Encoding.UTF8.GetBytes(text))
|
||||
{
|
||||
hash ^= c;
|
||||
hash *= prime;
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
|
||||
public static class NameMangler
|
||||
{
|
||||
public static string Mangle(string module, string name, NubType type)
|
||||
{
|
||||
var canonical = TypeEncoder.Encode(type);
|
||||
var hash = Hashing.Fnv1a64(canonical);
|
||||
|
||||
return $"nub_{Sanitize(module)}_{Sanitize(name)}_{hash:x16}";
|
||||
}
|
||||
|
||||
private static string Sanitize(string s)
|
||||
{
|
||||
var sb = new StringBuilder(s.Length);
|
||||
foreach (var c in s)
|
||||
{
|
||||
if (char.IsLetterOrDigit(c))
|
||||
sb.Append(c);
|
||||
else
|
||||
sb.Append('_');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
1101
compiler/Parser.cs
Normal file
1101
compiler/Parser.cs
Normal file
File diff suppressed because it is too large
Load Diff
179
compiler/Program.cs
Normal file
179
compiler/Program.cs
Normal file
@@ -0,0 +1,179 @@
|
||||
using System.Diagnostics;
|
||||
using Compiler;
|
||||
|
||||
var nubFiles = new List<string>();
|
||||
var libFiles = new List<string>();
|
||||
var compileLib = false;
|
||||
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
string arg = args[i];
|
||||
|
||||
if (arg.StartsWith("--type="))
|
||||
{
|
||||
var value = arg.Split("--type=")[1];
|
||||
switch (value)
|
||||
{
|
||||
case "lib":
|
||||
compileLib = true;
|
||||
break;
|
||||
case "exe":
|
||||
compileLib = false;
|
||||
break;
|
||||
default:
|
||||
DiagnosticFormatter.Print(Diagnostic.Error("Type must be 'exe' or 'lib'").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
else if (arg.EndsWith(".nub"))
|
||||
{
|
||||
nubFiles.Add(arg);
|
||||
}
|
||||
else if (arg.EndsWith(".nublib"))
|
||||
{
|
||||
libFiles.Add(arg);
|
||||
}
|
||||
else if (arg == "--help")
|
||||
{
|
||||
Console.WriteLine("""
|
||||
Usage: nubc [options] <files>
|
||||
|
||||
Options:
|
||||
--type=exe Compile the input files into an executable (default)
|
||||
--type=lib Compile the input files into a library
|
||||
--help Show this help message
|
||||
|
||||
Files:
|
||||
*.nub Nub source files to compile
|
||||
*.nublib Precompiled Nub libraries to link
|
||||
|
||||
Example:
|
||||
nubc --type=exe main.nub utils.nub math.nublib
|
||||
""");
|
||||
}
|
||||
else
|
||||
{
|
||||
DiagnosticFormatter.Print(Diagnostic.Error($"Unrecognized option '{arg}'").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
var moduleGraphBuilder = ModuleGraph.CreateBuilder();
|
||||
var asts = new List<Ast>();
|
||||
var archivePaths = new List<string>();
|
||||
|
||||
foreach (var libPath in libFiles)
|
||||
{
|
||||
var lib = NubLib.Unpack(libPath);
|
||||
archivePaths.Add(lib.ArchivePath);
|
||||
moduleGraphBuilder.AddManifest(lib.Manifest);
|
||||
}
|
||||
|
||||
foreach (var fileName in nubFiles)
|
||||
{
|
||||
var file = File.ReadAllText(fileName);
|
||||
|
||||
var tokens = Tokenizer.Tokenize(fileName, file, out var tokenizerDiagnostics);
|
||||
|
||||
foreach (var diagnostic in tokenizerDiagnostics)
|
||||
DiagnosticFormatter.Print(diagnostic, Console.Error);
|
||||
|
||||
if (tokens == null)
|
||||
return 1;
|
||||
|
||||
var ast = Parser.Parse(fileName, tokens, out var parserDiagnostics);
|
||||
|
||||
foreach (var diagnostic in parserDiagnostics)
|
||||
DiagnosticFormatter.Print(diagnostic, Console.Error);
|
||||
|
||||
if (ast == null)
|
||||
return 1;
|
||||
|
||||
moduleGraphBuilder.AddAst(ast);
|
||||
asts.Add(ast);
|
||||
}
|
||||
|
||||
var moduleGraph = moduleGraphBuilder.Build(out var moduleGraphDiagnostics);
|
||||
|
||||
foreach (var diagnostic in moduleGraphDiagnostics)
|
||||
DiagnosticFormatter.Print(diagnostic, Console.Error);
|
||||
|
||||
if (moduleGraph == null)
|
||||
return 1;
|
||||
|
||||
var functions = new List<TypedNodeDefinitionFunc>();
|
||||
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
foreach (var func in ast.Definitions.OfType<NodeDefinitionFunc>())
|
||||
{
|
||||
var typedFunction = TypeChecker.CheckFunction(ast.FileName, ast.ModuleName.Ident, func, moduleGraph, out var typeCheckerDiagnostics);
|
||||
|
||||
foreach (var diagnostic in typeCheckerDiagnostics)
|
||||
DiagnosticFormatter.Print(diagnostic, Console.Error);
|
||||
|
||||
if (typedFunction == null)
|
||||
return 1;
|
||||
|
||||
functions.Add(typedFunction);
|
||||
}
|
||||
}
|
||||
|
||||
if (Directory.Exists(".build"))
|
||||
{
|
||||
CleanDirectory(".build");
|
||||
}
|
||||
else
|
||||
{
|
||||
Directory.CreateDirectory(".build");
|
||||
}
|
||||
|
||||
string? entryPoint = null;
|
||||
|
||||
if (!compileLib)
|
||||
{
|
||||
if (!moduleGraph.TryResolveIdentifier("main", "main", true, out var info) || info.Type is not NubTypeFunc entryPointType)
|
||||
{
|
||||
DiagnosticFormatter.Print(Diagnostic.Error("func main::main(): i32 is not defined. If you wanted to compile as a library, specify --type=lib").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!entryPointType.ReturnType.IsAssignableTo(NubTypeSInt.Get(32)))
|
||||
{
|
||||
DiagnosticFormatter.Print(Diagnostic.Error($"Entrypoint must return an i32 (currently '{entryPointType.ReturnType}')").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
entryPoint = info.MangledName;
|
||||
}
|
||||
|
||||
var outFile = Generator.Emit(functions, moduleGraph, entryPoint);
|
||||
|
||||
if (compileLib)
|
||||
{
|
||||
Process.Start("gcc", ["-Og", "-g", "-Wall", "-Werror", "-c", "-o", ".build/out.o", outFile, .. archivePaths]).WaitForExit();
|
||||
Process.Start("ar", ["rcs", ".build/out.a", ".build/out.o"]).WaitForExit();
|
||||
NubLib.Pack(".build/out.nublib", ".build/out.a", Manifest.Create(moduleGraph));
|
||||
}
|
||||
else
|
||||
{
|
||||
Process.Start("gcc", ["-Og", "-g", "-Wall", "-Werror", "-o", ".build/out", outFile, .. archivePaths]).WaitForExit();
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
static void CleanDirectory(string dirName)
|
||||
{
|
||||
var dir = new DirectoryInfo(dirName);
|
||||
|
||||
foreach (var file in dir.GetFiles())
|
||||
{
|
||||
file.Delete();
|
||||
}
|
||||
|
||||
foreach (var subdir in dir.GetDirectories())
|
||||
{
|
||||
CleanDirectory(subdir.FullName);
|
||||
subdir.Delete();
|
||||
}
|
||||
}
|
||||
643
compiler/Tokenizer.cs
Normal file
643
compiler/Tokenizer.cs
Normal file
@@ -0,0 +1,643 @@
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
public class Tokenizer
|
||||
{
|
||||
public static List<Token>? Tokenize(string fileName, string contents, out List<Diagnostic> diagnostics)
|
||||
{
|
||||
return new Tokenizer(fileName, contents).Tokenize(out diagnostics);
|
||||
}
|
||||
|
||||
private Tokenizer(string fileName, string contents)
|
||||
{
|
||||
this.fileName = fileName;
|
||||
this.contents = contents;
|
||||
}
|
||||
|
||||
private readonly string fileName;
|
||||
private readonly string contents;
|
||||
private int index;
|
||||
private int line = 1;
|
||||
private int column = 1;
|
||||
|
||||
private List<Token>? Tokenize(out List<Diagnostic> diagnostics)
|
||||
{
|
||||
var tokens = new List<Token>();
|
||||
diagnostics = [];
|
||||
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!TryPeek(out var c))
|
||||
break;
|
||||
|
||||
if (char.IsWhiteSpace(c))
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '/' && Peek(1) == '/')
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
while (TryPeek(out c) && c != '\n')
|
||||
Consume();
|
||||
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
tokens.Add(ParseToken());
|
||||
}
|
||||
catch (CompileException e)
|
||||
{
|
||||
diagnostics.Add(e.Diagnostic);
|
||||
// Skip current token if parsing failed, this prevents an infinite loop when ParseToken fails before consuming any tokens
|
||||
TryConsume(out _);
|
||||
}
|
||||
}
|
||||
|
||||
if (diagnostics.Any(x => x.Severity == Diagnostic.DiagnosticSeverity.Error))
|
||||
return null;
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private Token ParseToken()
|
||||
{
|
||||
var startColumn = column;
|
||||
var c = Peek()!.Value;
|
||||
|
||||
if (char.IsDigit(c))
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '0' when Peek(1) is 'x':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
|
||||
var parsed = BigInteger.Zero;
|
||||
var seenDigit = false;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!char.IsAsciiHexDigit(c))
|
||||
break;
|
||||
|
||||
seenDigit = true;
|
||||
parsed <<= 4;
|
||||
|
||||
Consume();
|
||||
parsed += c switch
|
||||
{
|
||||
>= '0' and <= '9' => c - '0',
|
||||
>= 'a' and <= 'f' => c - 'a' + 10,
|
||||
>= 'A' and <= 'F' => c - 'A' + 10,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
|
||||
if (!seenDigit)
|
||||
throw new CompileException(Diagnostic.Error("Expected hexadecimal digits after 0x").At(fileName, line, startColumn, column - startColumn).Build());
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
case '0' when Peek(1) is 'b':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
|
||||
var parsed = BigInteger.Zero;
|
||||
var seenDigit = false;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c is not '0' and not '1')
|
||||
break;
|
||||
|
||||
seenDigit = true;
|
||||
parsed <<= 1;
|
||||
|
||||
if (Consume() == '1')
|
||||
parsed += BigInteger.One;
|
||||
}
|
||||
|
||||
if (!seenDigit)
|
||||
throw new CompileException(Diagnostic.Error("Expected binary digits after 0b").At(fileName, line, startColumn, column - startColumn).Build());
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
default:
|
||||
{
|
||||
var parsed = BigInteger.Zero;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!char.IsDigit(c))
|
||||
break;
|
||||
|
||||
parsed *= 10;
|
||||
parsed += Consume() - '0';
|
||||
}
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '"':
|
||||
{
|
||||
Consume();
|
||||
var buf = new StringBuilder();
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (!TryPeek(out c))
|
||||
throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 0).Build());
|
||||
|
||||
if (c == '"')
|
||||
break;
|
||||
|
||||
if (c == '\n')
|
||||
throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 1).Build());
|
||||
|
||||
buf.Append(Consume());
|
||||
}
|
||||
|
||||
Consume();
|
||||
return new TokenStringLiteral(line, startColumn, column - startColumn, buf.ToString());
|
||||
}
|
||||
|
||||
case '{':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenCurly);
|
||||
}
|
||||
case '}':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseCurly);
|
||||
}
|
||||
case '[':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenSquare);
|
||||
}
|
||||
case ']':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseSquare);
|
||||
}
|
||||
case '(':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenParen);
|
||||
}
|
||||
case ')':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseParen);
|
||||
}
|
||||
case ',':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Comma);
|
||||
}
|
||||
case '.':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Period);
|
||||
}
|
||||
case ':' when Peek(1) is ':':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ColonColon);
|
||||
}
|
||||
case ':':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Colon);
|
||||
}
|
||||
case '^':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Caret);
|
||||
}
|
||||
case '!' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.BangEqual);
|
||||
}
|
||||
case '!':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Bang);
|
||||
}
|
||||
case '=' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.EqualEqual);
|
||||
}
|
||||
case '=':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Equal);
|
||||
}
|
||||
case '<' when Peek(1) is '<':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanLessThan);
|
||||
}
|
||||
case '<' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanEqual);
|
||||
}
|
||||
case '<':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThan);
|
||||
}
|
||||
case '>' when Peek(1) is '>':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanGreaterThan);
|
||||
}
|
||||
case '>' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanEqual);
|
||||
}
|
||||
case '>':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThan);
|
||||
}
|
||||
case '+' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PlusEqual);
|
||||
}
|
||||
case '+':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Plus);
|
||||
}
|
||||
case '-' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.MinusEqual);
|
||||
}
|
||||
case '-':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Minus);
|
||||
}
|
||||
case '*' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.StarEqual);
|
||||
}
|
||||
case '*':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Star);
|
||||
}
|
||||
case '/' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlashEqual);
|
||||
}
|
||||
case '/':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlash);
|
||||
}
|
||||
case '%' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PercentEqual);
|
||||
}
|
||||
case '%':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Percent);
|
||||
}
|
||||
case '&' when Peek(1) is '&':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.AmpersandAmpersand);
|
||||
}
|
||||
case '&':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Ampersand);
|
||||
}
|
||||
case '|' when Peek(1) is '|':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PipePipe);
|
||||
}
|
||||
case '|':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Pipe);
|
||||
}
|
||||
default:
|
||||
{
|
||||
if (char.IsLetter(c) || c == '_')
|
||||
{
|
||||
var buf = new StringBuilder();
|
||||
|
||||
while (TryPeek(out c) && (char.IsLetterOrDigit(c) || c == '_'))
|
||||
buf.Append(Consume());
|
||||
|
||||
var value = buf.ToString();
|
||||
|
||||
return value switch
|
||||
{
|
||||
"func" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Func),
|
||||
"struct" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Struct),
|
||||
"packed" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Packed),
|
||||
"enum" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Enum),
|
||||
"new" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.New),
|
||||
"match" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Match),
|
||||
"let" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Let),
|
||||
"if" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.If),
|
||||
"else" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Else),
|
||||
"while" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.While),
|
||||
"for" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.For),
|
||||
"in" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.In),
|
||||
"return" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Return),
|
||||
"module" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Module),
|
||||
"export" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Export),
|
||||
"extern" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Extern),
|
||||
"true" => new TokenBoolLiteral(line, startColumn, column - startColumn, true),
|
||||
"false" => new TokenBoolLiteral(line, startColumn, column - startColumn, false),
|
||||
_ => new TokenIdent(line, startColumn, column - startColumn, value)
|
||||
};
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error($"Unexpected character '{c}'").At(fileName, line, column, 1).Build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryConsume(out char c)
|
||||
{
|
||||
if (index >= contents.Length)
|
||||
{
|
||||
c = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
c = contents[index];
|
||||
|
||||
if (c == '\n')
|
||||
{
|
||||
line += 1;
|
||||
column = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
column += 1;
|
||||
}
|
||||
|
||||
index += 1;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private char Consume()
|
||||
{
|
||||
if (!TryConsume(out var c))
|
||||
throw new CompileException(Diagnostic.Error("Unexpected end of file").At(fileName, line, column, 0).Build());
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
private char? Peek(int offset = 0)
|
||||
{
|
||||
if (index + offset >= contents.Length)
|
||||
return null;
|
||||
|
||||
return contents[index + offset];
|
||||
}
|
||||
|
||||
private bool TryPeek(out char c)
|
||||
{
|
||||
if (index >= contents.Length)
|
||||
{
|
||||
c = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
c = contents[index];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class Token(int line, int column, int length)
|
||||
{
|
||||
public int Line { get; } = line;
|
||||
public int Column { get; } = column;
|
||||
public int Length { get; } = length;
|
||||
}
|
||||
|
||||
public class TokenIdent(int line, int column, int length, string ident) : Token(line, column, length)
|
||||
{
|
||||
public string Ident { get; } = ident;
|
||||
}
|
||||
|
||||
public class TokenIntLiteral(int line, int column, int length, BigInteger value) : Token(line, column, length)
|
||||
{
|
||||
public BigInteger Value { get; } = value;
|
||||
}
|
||||
|
||||
public class TokenStringLiteral(int line, int column, int length, string value) : Token(line, column, length)
|
||||
{
|
||||
public string Value { get; } = value;
|
||||
}
|
||||
|
||||
public class TokenBoolLiteral(int line, int column, int length, bool value) : Token(line, column, length)
|
||||
{
|
||||
public bool Value { get; } = value;
|
||||
}
|
||||
|
||||
public enum Symbol
|
||||
{
|
||||
OpenCurly,
|
||||
CloseCurly,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
OpenSquare,
|
||||
CloseSquare,
|
||||
Comma,
|
||||
Period,
|
||||
Colon,
|
||||
ColonColon,
|
||||
Caret,
|
||||
Bang,
|
||||
Equal,
|
||||
EqualEqual,
|
||||
BangEqual,
|
||||
LessThan,
|
||||
LessThanLessThan,
|
||||
LessThanEqual,
|
||||
GreaterThan,
|
||||
GreaterThanGreaterThan,
|
||||
GreaterThanEqual,
|
||||
Plus,
|
||||
PlusEqual,
|
||||
Minus,
|
||||
MinusEqual,
|
||||
Star,
|
||||
StarEqual,
|
||||
ForwardSlash,
|
||||
ForwardSlashEqual,
|
||||
Percent,
|
||||
PercentEqual,
|
||||
Ampersand,
|
||||
AmpersandAmpersand,
|
||||
Pipe,
|
||||
PipePipe,
|
||||
}
|
||||
|
||||
public class TokenSymbol(int line, int column, int length, Symbol symbol) : Token(line, column, length)
|
||||
{
|
||||
public Symbol Symbol { get; } = symbol;
|
||||
}
|
||||
|
||||
public enum Keyword
|
||||
{
|
||||
Func,
|
||||
Struct,
|
||||
Packed,
|
||||
Enum,
|
||||
New,
|
||||
Match,
|
||||
Let,
|
||||
If,
|
||||
Else,
|
||||
While,
|
||||
For,
|
||||
In,
|
||||
Return,
|
||||
Module,
|
||||
Export,
|
||||
Extern,
|
||||
}
|
||||
|
||||
public class TokenKeyword(int line, int column, int length, Keyword keyword) : Token(line, column, length)
|
||||
{
|
||||
public Keyword Keyword { get; } = keyword;
|
||||
}
|
||||
|
||||
public static class TokenExtensions
|
||||
{
|
||||
public static string AsString(this Symbol symbol)
|
||||
{
|
||||
return symbol switch
|
||||
{
|
||||
Symbol.OpenCurly => "{",
|
||||
Symbol.CloseCurly => "}",
|
||||
Symbol.OpenParen => "(",
|
||||
Symbol.CloseParen => ")",
|
||||
Symbol.OpenSquare => "[",
|
||||
Symbol.CloseSquare => "]",
|
||||
Symbol.Comma => ",",
|
||||
Symbol.Period => ".",
|
||||
Symbol.Colon => ":",
|
||||
Symbol.ColonColon => "::",
|
||||
Symbol.Caret => "^",
|
||||
Symbol.Bang => "!",
|
||||
Symbol.Equal => "=",
|
||||
Symbol.EqualEqual => "==",
|
||||
Symbol.BangEqual => "!=",
|
||||
Symbol.LessThan => "<",
|
||||
Symbol.LessThanLessThan => "<<",
|
||||
Symbol.LessThanEqual => "<=",
|
||||
Symbol.GreaterThan => ">",
|
||||
Symbol.GreaterThanGreaterThan => ">>",
|
||||
Symbol.GreaterThanEqual => ">=",
|
||||
Symbol.Plus => "+",
|
||||
Symbol.PlusEqual => "+=",
|
||||
Symbol.Minus => "-",
|
||||
Symbol.MinusEqual => "-=",
|
||||
Symbol.Star => "*",
|
||||
Symbol.StarEqual => "*=",
|
||||
Symbol.ForwardSlash => "/",
|
||||
Symbol.ForwardSlashEqual => "/=",
|
||||
Symbol.Percent => "%",
|
||||
Symbol.PercentEqual => "%=",
|
||||
Symbol.Ampersand => "&",
|
||||
Symbol.AmpersandAmpersand => "&&",
|
||||
Symbol.Pipe => "|",
|
||||
Symbol.PipePipe => "||",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(symbol), symbol, null)
|
||||
};
|
||||
}
|
||||
|
||||
public static string AsString(this Keyword symbol)
|
||||
{
|
||||
return symbol switch
|
||||
{
|
||||
Keyword.Func => "func",
|
||||
Keyword.Struct => "struct",
|
||||
Keyword.Packed => "packed",
|
||||
Keyword.Enum => "enum",
|
||||
Keyword.New => "new",
|
||||
Keyword.Match => "enum",
|
||||
Keyword.Let => "let",
|
||||
Keyword.If => "if",
|
||||
Keyword.Else => "else",
|
||||
Keyword.While => "while",
|
||||
Keyword.For => "for",
|
||||
Keyword.In => "in",
|
||||
Keyword.Return => "return",
|
||||
Keyword.Module => "module",
|
||||
Keyword.Export => "export",
|
||||
Keyword.Extern => "extern",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(symbol), symbol, null)
|
||||
};
|
||||
}
|
||||
}
|
||||
1106
compiler/TypeChecker.cs
Normal file
1106
compiler/TypeChecker.cs
Normal file
File diff suppressed because it is too large
Load Diff
2
examples/.gitignore
vendored
2
examples/.gitignore
vendored
@@ -1,3 +1 @@
|
||||
.build
|
||||
out.a
|
||||
out
|
||||
21
examples/build
Executable file
21
examples/build
Executable file
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR=$(dirname "$0")
|
||||
|
||||
pushd $SCRIPT_DIR
|
||||
pushd ../compiler
|
||||
dotnet build -c Release
|
||||
popd
|
||||
|
||||
pushd core
|
||||
time ../../compiler/bin/Release/net9.0/Compiler sys.nub print.nub --type=lib
|
||||
popd
|
||||
|
||||
pushd program
|
||||
time ../../compiler/bin/Release/net9.0/Compiler main.nub ../core/.build/out.nublib
|
||||
popd
|
||||
|
||||
./program/.build/out
|
||||
popd
|
||||
10
examples/core/print.nub
Normal file
10
examples/core/print.nub
Normal file
@@ -0,0 +1,10 @@
|
||||
module core
|
||||
|
||||
export func print(text: string) {
|
||||
sys::write(0, text.ptr, text.length)
|
||||
}
|
||||
|
||||
export func println(text: string) {
|
||||
print(text)
|
||||
print("\n")
|
||||
}
|
||||
5
examples/core/sys.nub
Normal file
5
examples/core/sys.nub
Normal file
@@ -0,0 +1,5 @@
|
||||
module sys
|
||||
|
||||
export extern func read(fd: u32, buf: ^char, count: u64): i64
|
||||
export extern func write(fd: u32, buf: ^char, count: u64): i64
|
||||
export extern func open(fileName: ^char, flags: i32, mode: u16): i64
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
obj=$(nubc main.nub)
|
||||
clang $obj -o .build/out
|
||||
@@ -1,24 +0,0 @@
|
||||
module "main"
|
||||
|
||||
extern "puts" func puts(text: cstring)
|
||||
|
||||
struct X
|
||||
{
|
||||
points: []i32
|
||||
}
|
||||
|
||||
extern "main" func main(argc: i64, argv: [?]cstring): i64
|
||||
{
|
||||
let f: []cstring = ["1", "2", "3"]
|
||||
|
||||
puts(f[0])
|
||||
puts(f[1])
|
||||
puts(f[2])
|
||||
|
||||
for num in f
|
||||
{
|
||||
puts(num)
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
32
examples/program/main.nub
Normal file
32
examples/program/main.nub
Normal file
@@ -0,0 +1,32 @@
|
||||
module main
|
||||
|
||||
struct Human {
|
||||
name: string
|
||||
age: i32
|
||||
}
|
||||
|
||||
enum Message {
|
||||
Quit
|
||||
Say: string
|
||||
}
|
||||
|
||||
func main(): i32 {
|
||||
|
||||
let x = new string("test".ptr) + " " + "uwu"
|
||||
core::println(x)
|
||||
|
||||
let messages: []Message = [new Message::Say("first"), new Message::Quit]
|
||||
|
||||
for message in messages {
|
||||
match message {
|
||||
Say msg {
|
||||
core::println(msg)
|
||||
}
|
||||
Quit {
|
||||
core::println("quit")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
obj=$(nubc main.nub generated/raylib.nub)
|
||||
clang $obj raylib-5.5_linux_amd64/lib/libraylib.a -lm -o .build/out
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,190 +0,0 @@
|
||||
module "raymath"
|
||||
|
||||
export struct Vector2
|
||||
{
|
||||
x: f32
|
||||
y: f32
|
||||
}
|
||||
export struct Vector3
|
||||
{
|
||||
x: f32
|
||||
y: f32
|
||||
z: f32
|
||||
}
|
||||
export struct Vector4
|
||||
{
|
||||
x: f32
|
||||
y: f32
|
||||
z: f32
|
||||
w: f32
|
||||
}
|
||||
export struct Matrix
|
||||
{
|
||||
m0: f32
|
||||
m4: f32
|
||||
m8: f32
|
||||
m12: f32
|
||||
m1: f32
|
||||
m5: f32
|
||||
m9: f32
|
||||
m13: f32
|
||||
m2: f32
|
||||
m6: f32
|
||||
m10: f32
|
||||
m14: f32
|
||||
m3: f32
|
||||
m7: f32
|
||||
m11: f32
|
||||
m15: f32
|
||||
}
|
||||
export struct float3
|
||||
{
|
||||
v: [3]f32
|
||||
}
|
||||
export struct float16
|
||||
{
|
||||
v: [16]f32
|
||||
}
|
||||
export extern "Clamp" func Clamp(value: f32, min: f32, max: f32): f32
|
||||
export extern "Lerp" func Lerp(start: f32, end: f32, amount: f32): f32
|
||||
export extern "Normalize" func Normalize(value: f32, start: f32, end: f32): f32
|
||||
export extern "Remap" func Remap(value: f32, inputStart: f32, inputEnd: f32, outputStart: f32, outputEnd: f32): f32
|
||||
export extern "Wrap" func Wrap(value: f32, min: f32, max: f32): f32
|
||||
export extern "FloatEquals" func FloatEquals(x: f32, y: f32): i32
|
||||
export extern "Vector2Zero" func Vector2Zero(): Vector2
|
||||
export extern "Vector2One" func Vector2One(): Vector2
|
||||
export extern "Vector2Add" func Vector2Add(v1: Vector2, v2: Vector2): Vector2
|
||||
export extern "Vector2AddValue" func Vector2AddValue(v: Vector2, add: f32): Vector2
|
||||
export extern "Vector2Subtract" func Vector2Subtract(v1: Vector2, v2: Vector2): Vector2
|
||||
export extern "Vector2SubtractValue" func Vector2SubtractValue(v: Vector2, sub: f32): Vector2
|
||||
export extern "Vector2Length" func Vector2Length(v: Vector2): f32
|
||||
export extern "Vector2LengthSqr" func Vector2LengthSqr(v: Vector2): f32
|
||||
export extern "Vector2DotProduct" func Vector2DotProduct(v1: Vector2, v2: Vector2): f32
|
||||
export extern "Vector2Distance" func Vector2Distance(v1: Vector2, v2: Vector2): f32
|
||||
export extern "Vector2DistanceSqr" func Vector2DistanceSqr(v1: Vector2, v2: Vector2): f32
|
||||
export extern "Vector2Angle" func Vector2Angle(v1: Vector2, v2: Vector2): f32
|
||||
export extern "Vector2LineAngle" func Vector2LineAngle(start: Vector2, end: Vector2): f32
|
||||
export extern "Vector2Scale" func Vector2Scale(v: Vector2, scale: f32): Vector2
|
||||
export extern "Vector2Multiply" func Vector2Multiply(v1: Vector2, v2: Vector2): Vector2
|
||||
export extern "Vector2Negate" func Vector2Negate(v: Vector2): Vector2
|
||||
export extern "Vector2Divide" func Vector2Divide(v1: Vector2, v2: Vector2): Vector2
|
||||
export extern "Vector2Normalize" func Vector2Normalize(v: Vector2): Vector2
|
||||
export extern "Vector2Transform" func Vector2Transform(v: Vector2, mat: Matrix): Vector2
|
||||
export extern "Vector2Lerp" func Vector2Lerp(v1: Vector2, v2: Vector2, amount: f32): Vector2
|
||||
export extern "Vector2Reflect" func Vector2Reflect(v: Vector2, normal: Vector2): Vector2
|
||||
export extern "Vector2Min" func Vector2Min(v1: Vector2, v2: Vector2): Vector2
|
||||
export extern "Vector2Max" func Vector2Max(v1: Vector2, v2: Vector2): Vector2
|
||||
export extern "Vector2Rotate" func Vector2Rotate(v: Vector2, angle: f32): Vector2
|
||||
export extern "Vector2MoveTowards" func Vector2MoveTowards(v: Vector2, target: Vector2, maxDistance: f32): Vector2
|
||||
export extern "Vector2Invert" func Vector2Invert(v: Vector2): Vector2
|
||||
export extern "Vector2Clamp" func Vector2Clamp(v: Vector2, min: Vector2, max: Vector2): Vector2
|
||||
export extern "Vector2ClampValue" func Vector2ClampValue(v: Vector2, min: f32, max: f32): Vector2
|
||||
export extern "Vector2Equals" func Vector2Equals(p: Vector2, q: Vector2): i32
|
||||
export extern "Vector2Refract" func Vector2Refract(v: Vector2, n: Vector2, r: f32): Vector2
|
||||
export extern "Vector3Zero" func Vector3Zero(): Vector3
|
||||
export extern "Vector3One" func Vector3One(): Vector3
|
||||
export extern "Vector3Add" func Vector3Add(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3AddValue" func Vector3AddValue(v: Vector3, add: f32): Vector3
|
||||
export extern "Vector3Subtract" func Vector3Subtract(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3SubtractValue" func Vector3SubtractValue(v: Vector3, sub: f32): Vector3
|
||||
export extern "Vector3Scale" func Vector3Scale(v: Vector3, scalar: f32): Vector3
|
||||
export extern "Vector3Multiply" func Vector3Multiply(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3CrossProduct" func Vector3CrossProduct(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3Perpendicular" func Vector3Perpendicular(v: Vector3): Vector3
|
||||
export extern "Vector3Length" func Vector3Length(v: Vector3): f32
|
||||
export extern "Vector3LengthSqr" func Vector3LengthSqr(v: Vector3): f32
|
||||
export extern "Vector3DotProduct" func Vector3DotProduct(v1: Vector3, v2: Vector3): f32
|
||||
export extern "Vector3Distance" func Vector3Distance(v1: Vector3, v2: Vector3): f32
|
||||
export extern "Vector3DistanceSqr" func Vector3DistanceSqr(v1: Vector3, v2: Vector3): f32
|
||||
export extern "Vector3Angle" func Vector3Angle(v1: Vector3, v2: Vector3): f32
|
||||
export extern "Vector3Negate" func Vector3Negate(v: Vector3): Vector3
|
||||
export extern "Vector3Divide" func Vector3Divide(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3Normalize" func Vector3Normalize(v: Vector3): Vector3
|
||||
export extern "Vector3Project" func Vector3Project(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3Reject" func Vector3Reject(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3OrthoNormalize" func Vector3OrthoNormalize(v1: ^Vector3, v2: ^Vector3): void
|
||||
export extern "Vector3Transform" func Vector3Transform(v: Vector3, mat: Matrix): Vector3
|
||||
export extern "Vector3RotateByQuaternion" func Vector3RotateByQuaternion(v: Vector3, q: Vector4): Vector3
|
||||
export extern "Vector3RotateByAxisAngle" func Vector3RotateByAxisAngle(v: Vector3, axis: Vector3, angle: f32): Vector3
|
||||
export extern "Vector3MoveTowards" func Vector3MoveTowards(v: Vector3, target: Vector3, maxDistance: f32): Vector3
|
||||
export extern "Vector3Lerp" func Vector3Lerp(v1: Vector3, v2: Vector3, amount: f32): Vector3
|
||||
export extern "Vector3CubicHermite" func Vector3CubicHermite(v1: Vector3, tangent1: Vector3, v2: Vector3, tangent2: Vector3, amount: f32): Vector3
|
||||
export extern "Vector3Reflect" func Vector3Reflect(v: Vector3, normal: Vector3): Vector3
|
||||
export extern "Vector3Min" func Vector3Min(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3Max" func Vector3Max(v1: Vector3, v2: Vector3): Vector3
|
||||
export extern "Vector3Barycenter" func Vector3Barycenter(p: Vector3, a: Vector3, b: Vector3, c: Vector3): Vector3
|
||||
export extern "Vector3Unproject" func Vector3Unproject(source: Vector3, projection: Matrix, view: Matrix): Vector3
|
||||
export extern "Vector3ToFloatV" func Vector3ToFloatV(v: Vector3): float3
|
||||
export extern "Vector3Invert" func Vector3Invert(v: Vector3): Vector3
|
||||
export extern "Vector3Clamp" func Vector3Clamp(v: Vector3, min: Vector3, max: Vector3): Vector3
|
||||
export extern "Vector3ClampValue" func Vector3ClampValue(v: Vector3, min: f32, max: f32): Vector3
|
||||
export extern "Vector3Equals" func Vector3Equals(p: Vector3, q: Vector3): i32
|
||||
export extern "Vector3Refract" func Vector3Refract(v: Vector3, n: Vector3, r: f32): Vector3
|
||||
export extern "Vector4Zero" func Vector4Zero(): Vector4
|
||||
export extern "Vector4One" func Vector4One(): Vector4
|
||||
export extern "Vector4Add" func Vector4Add(v1: Vector4, v2: Vector4): Vector4
|
||||
export extern "Vector4AddValue" func Vector4AddValue(v: Vector4, add: f32): Vector4
|
||||
export extern "Vector4Subtract" func Vector4Subtract(v1: Vector4, v2: Vector4): Vector4
|
||||
export extern "Vector4SubtractValue" func Vector4SubtractValue(v: Vector4, add: f32): Vector4
|
||||
export extern "Vector4Length" func Vector4Length(v: Vector4): f32
|
||||
export extern "Vector4LengthSqr" func Vector4LengthSqr(v: Vector4): f32
|
||||
export extern "Vector4DotProduct" func Vector4DotProduct(v1: Vector4, v2: Vector4): f32
|
||||
export extern "Vector4Distance" func Vector4Distance(v1: Vector4, v2: Vector4): f32
|
||||
export extern "Vector4DistanceSqr" func Vector4DistanceSqr(v1: Vector4, v2: Vector4): f32
|
||||
export extern "Vector4Scale" func Vector4Scale(v: Vector4, scale: f32): Vector4
|
||||
export extern "Vector4Multiply" func Vector4Multiply(v1: Vector4, v2: Vector4): Vector4
|
||||
export extern "Vector4Negate" func Vector4Negate(v: Vector4): Vector4
|
||||
export extern "Vector4Divide" func Vector4Divide(v1: Vector4, v2: Vector4): Vector4
|
||||
export extern "Vector4Normalize" func Vector4Normalize(v: Vector4): Vector4
|
||||
export extern "Vector4Min" func Vector4Min(v1: Vector4, v2: Vector4): Vector4
|
||||
export extern "Vector4Max" func Vector4Max(v1: Vector4, v2: Vector4): Vector4
|
||||
export extern "Vector4Lerp" func Vector4Lerp(v1: Vector4, v2: Vector4, amount: f32): Vector4
|
||||
export extern "Vector4MoveTowards" func Vector4MoveTowards(v: Vector4, target: Vector4, maxDistance: f32): Vector4
|
||||
export extern "Vector4Invert" func Vector4Invert(v: Vector4): Vector4
|
||||
export extern "Vector4Equals" func Vector4Equals(p: Vector4, q: Vector4): i32
|
||||
export extern "MatrixDeterminant" func MatrixDeterminant(mat: Matrix): f32
|
||||
export extern "MatrixTrace" func MatrixTrace(mat: Matrix): f32
|
||||
export extern "MatrixTranspose" func MatrixTranspose(mat: Matrix): Matrix
|
||||
export extern "MatrixInvert" func MatrixInvert(mat: Matrix): Matrix
|
||||
export extern "MatrixIdentity" func MatrixIdentity(): Matrix
|
||||
export extern "MatrixAdd" func MatrixAdd(left: Matrix, right: Matrix): Matrix
|
||||
export extern "MatrixSubtract" func MatrixSubtract(left: Matrix, right: Matrix): Matrix
|
||||
export extern "MatrixMultiply" func MatrixMultiply(left: Matrix, right: Matrix): Matrix
|
||||
export extern "MatrixTranslate" func MatrixTranslate(x: f32, y: f32, z: f32): Matrix
|
||||
export extern "MatrixRotate" func MatrixRotate(axis: Vector3, angle: f32): Matrix
|
||||
export extern "MatrixRotateX" func MatrixRotateX(angle: f32): Matrix
|
||||
export extern "MatrixRotateY" func MatrixRotateY(angle: f32): Matrix
|
||||
export extern "MatrixRotateZ" func MatrixRotateZ(angle: f32): Matrix
|
||||
export extern "MatrixRotateXYZ" func MatrixRotateXYZ(angle: Vector3): Matrix
|
||||
export extern "MatrixRotateZYX" func MatrixRotateZYX(angle: Vector3): Matrix
|
||||
export extern "MatrixScale" func MatrixScale(x: f32, y: f32, z: f32): Matrix
|
||||
export extern "MatrixFrustum" func MatrixFrustum(left: f64, right: f64, bottom: f64, top: f64, nearPlane: f64, farPlane: f64): Matrix
|
||||
export extern "MatrixPerspective" func MatrixPerspective(fovY: f64, aspect: f64, nearPlane: f64, farPlane: f64): Matrix
|
||||
export extern "MatrixOrtho" func MatrixOrtho(left: f64, right: f64, bottom: f64, top: f64, nearPlane: f64, farPlane: f64): Matrix
|
||||
export extern "MatrixLookAt" func MatrixLookAt(eye: Vector3, target: Vector3, up: Vector3): Matrix
|
||||
export extern "MatrixToFloatV" func MatrixToFloatV(mat: Matrix): float16
|
||||
export extern "QuaternionAdd" func QuaternionAdd(q1: Vector4, q2: Vector4): Vector4
|
||||
export extern "QuaternionAddValue" func QuaternionAddValue(q: Vector4, add: f32): Vector4
|
||||
export extern "QuaternionSubtract" func QuaternionSubtract(q1: Vector4, q2: Vector4): Vector4
|
||||
export extern "QuaternionSubtractValue" func QuaternionSubtractValue(q: Vector4, sub: f32): Vector4
|
||||
export extern "QuaternionIdentity" func QuaternionIdentity(): Vector4
|
||||
export extern "QuaternionLength" func QuaternionLength(q: Vector4): f32
|
||||
export extern "QuaternionNormalize" func QuaternionNormalize(q: Vector4): Vector4
|
||||
export extern "QuaternionInvert" func QuaternionInvert(q: Vector4): Vector4
|
||||
export extern "QuaternionMultiply" func QuaternionMultiply(q1: Vector4, q2: Vector4): Vector4
|
||||
export extern "QuaternionScale" func QuaternionScale(q: Vector4, mul: f32): Vector4
|
||||
export extern "QuaternionDivide" func QuaternionDivide(q1: Vector4, q2: Vector4): Vector4
|
||||
export extern "QuaternionLerp" func QuaternionLerp(q1: Vector4, q2: Vector4, amount: f32): Vector4
|
||||
export extern "QuaternionNlerp" func QuaternionNlerp(q1: Vector4, q2: Vector4, amount: f32): Vector4
|
||||
export extern "QuaternionSlerp" func QuaternionSlerp(q1: Vector4, q2: Vector4, amount: f32): Vector4
|
||||
export extern "QuaternionCubicHermiteSpline" func QuaternionCubicHermiteSpline(q1: Vector4, outTangent1: Vector4, q2: Vector4, inTangent2: Vector4, t: f32): Vector4
|
||||
export extern "QuaternionFromVector3ToVector3" func QuaternionFromVector3ToVector3(from: Vector3, to: Vector3): Vector4
|
||||
export extern "QuaternionFromMatrix" func QuaternionFromMatrix(mat: Matrix): Vector4
|
||||
export extern "QuaternionToMatrix" func QuaternionToMatrix(q: Vector4): Matrix
|
||||
export extern "QuaternionFromAxisAngle" func QuaternionFromAxisAngle(axis: Vector3, angle: f32): Vector4
|
||||
export extern "QuaternionToAxisAngle" func QuaternionToAxisAngle(q: Vector4, outAxis: ^Vector3, outAngle: ^f32): void
|
||||
export extern "QuaternionFromEuler" func QuaternionFromEuler(pitch: f32, yaw: f32, roll: f32): Vector4
|
||||
export extern "QuaternionToEuler" func QuaternionToEuler(q: Vector4): Vector3
|
||||
export extern "QuaternionTransform" func QuaternionTransform(q: Vector4, mat: Matrix): Vector4
|
||||
export extern "QuaternionEquals" func QuaternionEquals(p: Vector4, q: Vector4): i32
|
||||
export extern "MatrixDecompose" func MatrixDecompose(mat: Matrix, translation: ^Vector3, rotation: ^Vector4, scale: ^Vector3): void
|
||||
@@ -1,202 +0,0 @@
|
||||
module "rlgl"
|
||||
|
||||
export struct Matrix
|
||||
{
|
||||
m0: f32
|
||||
m4: f32
|
||||
m8: f32
|
||||
m12: f32
|
||||
m1: f32
|
||||
m5: f32
|
||||
m9: f32
|
||||
m13: f32
|
||||
m2: f32
|
||||
m6: f32
|
||||
m10: f32
|
||||
m14: f32
|
||||
m3: f32
|
||||
m7: f32
|
||||
m11: f32
|
||||
m15: f32
|
||||
}
|
||||
export struct rlVertexBuffer
|
||||
{
|
||||
elementCount: i32
|
||||
vertices: ^f32
|
||||
texcoords: ^f32
|
||||
normals: ^f32
|
||||
colors: ^u8
|
||||
indices: ^u32
|
||||
vaoId: u32
|
||||
vboId: [5]u32
|
||||
}
|
||||
export struct rlDrawCall
|
||||
{
|
||||
mode: i32
|
||||
vertexCount: i32
|
||||
vertexAlignment: i32
|
||||
textureId: u32
|
||||
}
|
||||
export struct rlRenderBatch
|
||||
{
|
||||
bufferCount: i32
|
||||
currentBuffer: i32
|
||||
vertexBuffer: ^rlVertexBuffer
|
||||
draws: ^rlDrawCall
|
||||
drawCounter: i32
|
||||
currentDepth: f32
|
||||
}
|
||||
export extern "rlMatrixMode" func rlMatrixMode(mode: i32): void
|
||||
export extern "rlPushMatrix" func rlPushMatrix(): void
|
||||
export extern "rlPopMatrix" func rlPopMatrix(): void
|
||||
export extern "rlLoadIdentity" func rlLoadIdentity(): void
|
||||
export extern "rlTranslatef" func rlTranslatef(x: f32, y: f32, z: f32): void
|
||||
export extern "rlRotatef" func rlRotatef(angle: f32, x: f32, y: f32, z: f32): void
|
||||
export extern "rlScalef" func rlScalef(x: f32, y: f32, z: f32): void
|
||||
export extern "rlMultMatrixf" func rlMultMatrixf(matf: ^f32): void
|
||||
export extern "rlFrustum" func rlFrustum(left: f64, right: f64, bottom: f64, top: f64, znear: f64, zfar: f64): void
|
||||
export extern "rlOrtho" func rlOrtho(left: f64, right: f64, bottom: f64, top: f64, znear: f64, zfar: f64): void
|
||||
export extern "rlViewport" func rlViewport(x: i32, y: i32, width: i32, height: i32): void
|
||||
export extern "rlSetClipPlanes" func rlSetClipPlanes(nearPlane: f64, farPlane: f64): void
|
||||
export extern "rlGetCullDistanceNear" func rlGetCullDistanceNear(): f64
|
||||
export extern "rlGetCullDistanceFar" func rlGetCullDistanceFar(): f64
|
||||
export extern "rlBegin" func rlBegin(mode: i32): void
|
||||
export extern "rlEnd" func rlEnd(): void
|
||||
export extern "rlVertex2i" func rlVertex2i(x: i32, y: i32): void
|
||||
export extern "rlVertex2f" func rlVertex2f(x: f32, y: f32): void
|
||||
export extern "rlVertex3f" func rlVertex3f(x: f32, y: f32, z: f32): void
|
||||
export extern "rlTexCoord2f" func rlTexCoord2f(x: f32, y: f32): void
|
||||
export extern "rlNormal3f" func rlNormal3f(x: f32, y: f32, z: f32): void
|
||||
export extern "rlColor4ub" func rlColor4ub(r: u8, g: u8, b: u8, a: u8): void
|
||||
export extern "rlColor3f" func rlColor3f(x: f32, y: f32, z: f32): void
|
||||
export extern "rlColor4f" func rlColor4f(x: f32, y: f32, z: f32, w: f32): void
|
||||
export extern "rlEnableVertexArray" func rlEnableVertexArray(vaoId: u32): bool
|
||||
export extern "rlDisableVertexArray" func rlDisableVertexArray(): void
|
||||
export extern "rlEnableVertexBuffer" func rlEnableVertexBuffer(id: u32): void
|
||||
export extern "rlDisableVertexBuffer" func rlDisableVertexBuffer(): void
|
||||
export extern "rlEnableVertexBufferElement" func rlEnableVertexBufferElement(id: u32): void
|
||||
export extern "rlDisableVertexBufferElement" func rlDisableVertexBufferElement(): void
|
||||
export extern "rlEnableVertexAttribute" func rlEnableVertexAttribute(index: u32): void
|
||||
export extern "rlDisableVertexAttribute" func rlDisableVertexAttribute(index: u32): void
|
||||
export extern "rlActiveTextureSlot" func rlActiveTextureSlot(slot: i32): void
|
||||
export extern "rlEnableTexture" func rlEnableTexture(id: u32): void
|
||||
export extern "rlDisableTexture" func rlDisableTexture(): void
|
||||
export extern "rlEnableTextureCubemap" func rlEnableTextureCubemap(id: u32): void
|
||||
export extern "rlDisableTextureCubemap" func rlDisableTextureCubemap(): void
|
||||
export extern "rlTextureParameters" func rlTextureParameters(id: u32, param: i32, value: i32): void
|
||||
export extern "rlCubemapParameters" func rlCubemapParameters(id: u32, param: i32, value: i32): void
|
||||
export extern "rlEnableShader" func rlEnableShader(id: u32): void
|
||||
export extern "rlDisableShader" func rlDisableShader(): void
|
||||
export extern "rlEnableFramebuffer" func rlEnableFramebuffer(id: u32): void
|
||||
export extern "rlDisableFramebuffer" func rlDisableFramebuffer(): void
|
||||
export extern "rlGetActiveFramebuffer" func rlGetActiveFramebuffer(): u32
|
||||
export extern "rlActiveDrawBuffers" func rlActiveDrawBuffers(count: i32): void
|
||||
export extern "rlBlitFramebuffer" func rlBlitFramebuffer(srcX: i32, srcY: i32, srcWidth: i32, srcHeight: i32, dstX: i32, dstY: i32, dstWidth: i32, dstHeight: i32, bufferMask: i32): void
|
||||
export extern "rlBindFramebuffer" func rlBindFramebuffer(target: u32, framebuffer: u32): void
|
||||
export extern "rlEnableColorBlend" func rlEnableColorBlend(): void
|
||||
export extern "rlDisableColorBlend" func rlDisableColorBlend(): void
|
||||
export extern "rlEnableDepthTest" func rlEnableDepthTest(): void
|
||||
export extern "rlDisableDepthTest" func rlDisableDepthTest(): void
|
||||
export extern "rlEnableDepthMask" func rlEnableDepthMask(): void
|
||||
export extern "rlDisableDepthMask" func rlDisableDepthMask(): void
|
||||
export extern "rlEnableBackfaceCulling" func rlEnableBackfaceCulling(): void
|
||||
export extern "rlDisableBackfaceCulling" func rlDisableBackfaceCulling(): void
|
||||
export extern "rlColorMask" func rlColorMask(r: bool, g: bool, b: bool, a: bool): void
|
||||
export extern "rlSetCullFace" func rlSetCullFace(mode: i32): void
|
||||
export extern "rlEnableScissorTest" func rlEnableScissorTest(): void
|
||||
export extern "rlDisableScissorTest" func rlDisableScissorTest(): void
|
||||
export extern "rlScissor" func rlScissor(x: i32, y: i32, width: i32, height: i32): void
|
||||
export extern "rlEnableWireMode" func rlEnableWireMode(): void
|
||||
export extern "rlEnablePointMode" func rlEnablePointMode(): void
|
||||
export extern "rlDisableWireMode" func rlDisableWireMode(): void
|
||||
export extern "rlSetLineWidth" func rlSetLineWidth(width: f32): void
|
||||
export extern "rlGetLineWidth" func rlGetLineWidth(): f32
|
||||
export extern "rlEnableSmoothLines" func rlEnableSmoothLines(): void
|
||||
export extern "rlDisableSmoothLines" func rlDisableSmoothLines(): void
|
||||
export extern "rlEnableStereoRender" func rlEnableStereoRender(): void
|
||||
export extern "rlDisableStereoRender" func rlDisableStereoRender(): void
|
||||
export extern "rlIsStereoRenderEnabled" func rlIsStereoRenderEnabled(): bool
|
||||
export extern "rlClearColor" func rlClearColor(r: u8, g: u8, b: u8, a: u8): void
|
||||
export extern "rlClearScreenBuffers" func rlClearScreenBuffers(): void
|
||||
export extern "rlCheckErrors" func rlCheckErrors(): void
|
||||
export extern "rlSetBlendMode" func rlSetBlendMode(mode: i32): void
|
||||
export extern "rlSetBlendFactors" func rlSetBlendFactors(glSrcFactor: i32, glDstFactor: i32, glEquation: i32): void
|
||||
export extern "rlSetBlendFactorsSeparate" func rlSetBlendFactorsSeparate(glSrcRGB: i32, glDstRGB: i32, glSrcAlpha: i32, glDstAlpha: i32, glEqRGB: i32, glEqAlpha: i32): void
|
||||
export extern "rlglInit" func rlglInit(width: i32, height: i32): void
|
||||
export extern "rlglClose" func rlglClose(): void
|
||||
export extern "rlLoadExtensions" func rlLoadExtensions(loader: ^void): void
|
||||
export extern "rlGetVersion" func rlGetVersion(): i32
|
||||
export extern "rlSetFramebufferWidth" func rlSetFramebufferWidth(width: i32): void
|
||||
export extern "rlGetFramebufferWidth" func rlGetFramebufferWidth(): i32
|
||||
export extern "rlSetFramebufferHeight" func rlSetFramebufferHeight(height: i32): void
|
||||
export extern "rlGetFramebufferHeight" func rlGetFramebufferHeight(): i32
|
||||
export extern "rlGetTextureIdDefault" func rlGetTextureIdDefault(): u32
|
||||
export extern "rlGetShaderIdDefault" func rlGetShaderIdDefault(): u32
|
||||
export extern "rlGetShaderLocsDefault" func rlGetShaderLocsDefault(): ^i32
|
||||
export extern "rlLoadRenderBatch" func rlLoadRenderBatch(numBuffers: i32, bufferElements: i32): rlRenderBatch
|
||||
export extern "rlUnloadRenderBatch" func rlUnloadRenderBatch(batch: rlRenderBatch): void
|
||||
export extern "rlDrawRenderBatch" func rlDrawRenderBatch(batch: ^rlRenderBatch): void
|
||||
export extern "rlSetRenderBatchActive" func rlSetRenderBatchActive(batch: ^rlRenderBatch): void
|
||||
export extern "rlDrawRenderBatchActive" func rlDrawRenderBatchActive(): void
|
||||
export extern "rlCheckRenderBatchLimit" func rlCheckRenderBatchLimit(vCount: i32): bool
|
||||
export extern "rlSetTexture" func rlSetTexture(id: u32): void
|
||||
export extern "rlLoadVertexArray" func rlLoadVertexArray(): u32
|
||||
export extern "rlLoadVertexBuffer" func rlLoadVertexBuffer(buffer: ^void, size: i32, dynamic: bool): u32
|
||||
export extern "rlLoadVertexBufferElement" func rlLoadVertexBufferElement(buffer: ^void, size: i32, dynamic: bool): u32
|
||||
export extern "rlUpdateVertexBuffer" func rlUpdateVertexBuffer(bufferId: u32, data: ^void, dataSize: i32, offset: i32): void
|
||||
export extern "rlUpdateVertexBufferElements" func rlUpdateVertexBufferElements(id: u32, data: ^void, dataSize: i32, offset: i32): void
|
||||
export extern "rlUnloadVertexArray" func rlUnloadVertexArray(vaoId: u32): void
|
||||
export extern "rlUnloadVertexBuffer" func rlUnloadVertexBuffer(vboId: u32): void
|
||||
export extern "rlSetVertexAttribute" func rlSetVertexAttribute(index: u32, compSize: i32, type: i32, normalized: bool, stride: i32, offset: i32): void
|
||||
export extern "rlSetVertexAttributeDivisor" func rlSetVertexAttributeDivisor(index: u32, divisor: i32): void
|
||||
export extern "rlSetVertexAttributeDefault" func rlSetVertexAttributeDefault(locIndex: i32, value: ^void, attribType: i32, count: i32): void
|
||||
export extern "rlDrawVertexArray" func rlDrawVertexArray(offset: i32, count: i32): void
|
||||
export extern "rlDrawVertexArrayElements" func rlDrawVertexArrayElements(offset: i32, count: i32, buffer: ^void): void
|
||||
export extern "rlDrawVertexArrayInstanced" func rlDrawVertexArrayInstanced(offset: i32, count: i32, instances: i32): void
|
||||
export extern "rlDrawVertexArrayElementsInstanced" func rlDrawVertexArrayElementsInstanced(offset: i32, count: i32, buffer: ^void, instances: i32): void
|
||||
export extern "rlLoadTexture" func rlLoadTexture(data: ^void, width: i32, height: i32, format: i32, mipmapCount: i32): u32
|
||||
export extern "rlLoadTextureDepth" func rlLoadTextureDepth(width: i32, height: i32, useRenderBuffer: bool): u32
|
||||
export extern "rlLoadTextureCubemap" func rlLoadTextureCubemap(data: ^void, size: i32, format: i32, mipmapCount: i32): u32
|
||||
export extern "rlUpdateTexture" func rlUpdateTexture(id: u32, offsetX: i32, offsetY: i32, width: i32, height: i32, format: i32, data: ^void): void
|
||||
export extern "rlGetGlTextureFormats" func rlGetGlTextureFormats(format: i32, glInternalFormat: ^u32, glFormat: ^u32, glType: ^u32): void
|
||||
export extern "rlGetPixelFormatName" func rlGetPixelFormatName(format: u32): cstring
|
||||
export extern "rlUnloadTexture" func rlUnloadTexture(id: u32): void
|
||||
export extern "rlGenTextureMipmaps" func rlGenTextureMipmaps(id: u32, width: i32, height: i32, format: i32, mipmaps: ^i32): void
|
||||
export extern "rlReadTexturePixels" func rlReadTexturePixels(id: u32, width: i32, height: i32, format: i32): ^void
|
||||
export extern "rlReadScreenPixels" func rlReadScreenPixels(width: i32, height: i32): ^u8
|
||||
export extern "rlLoadFramebuffer" func rlLoadFramebuffer(): u32
|
||||
export extern "rlFramebufferAttach" func rlFramebufferAttach(fboId: u32, texId: u32, attachType: i32, texType: i32, mipLevel: i32): void
|
||||
export extern "rlFramebufferComplete" func rlFramebufferComplete(id: u32): bool
|
||||
export extern "rlUnloadFramebuffer" func rlUnloadFramebuffer(id: u32): void
|
||||
export extern "rlLoadShaderCode" func rlLoadShaderCode(vsCode: cstring, fsCode: cstring): u32
|
||||
export extern "rlCompileShader" func rlCompileShader(shaderCode: cstring, type: i32): u32
|
||||
export extern "rlLoadShaderProgram" func rlLoadShaderProgram(vShaderId: u32, fShaderId: u32): u32
|
||||
export extern "rlUnloadShaderProgram" func rlUnloadShaderProgram(id: u32): void
|
||||
export extern "rlGetLocationUniform" func rlGetLocationUniform(shaderId: u32, uniformName: cstring): i32
|
||||
export extern "rlGetLocationAttrib" func rlGetLocationAttrib(shaderId: u32, attribName: cstring): i32
|
||||
export extern "rlSetUniform" func rlSetUniform(locIndex: i32, value: ^void, uniformType: i32, count: i32): void
|
||||
export extern "rlSetUniformMatrix" func rlSetUniformMatrix(locIndex: i32, mat: Matrix): void
|
||||
export extern "rlSetUniformMatrices" func rlSetUniformMatrices(locIndex: i32, mat: ^Matrix, count: i32): void
|
||||
export extern "rlSetUniformSampler" func rlSetUniformSampler(locIndex: i32, textureId: u32): void
|
||||
export extern "rlSetShader" func rlSetShader(id: u32, locs: ^i32): void
|
||||
export extern "rlLoadComputeShaderProgram" func rlLoadComputeShaderProgram(shaderId: u32): u32
|
||||
export extern "rlComputeShaderDispatch" func rlComputeShaderDispatch(groupX: u32, groupY: u32, groupZ: u32): void
|
||||
export extern "rlLoadShaderBuffer" func rlLoadShaderBuffer(size: u32, data: ^void, usageHint: i32): u32
|
||||
export extern "rlUnloadShaderBuffer" func rlUnloadShaderBuffer(ssboId: u32): void
|
||||
export extern "rlUpdateShaderBuffer" func rlUpdateShaderBuffer(id: u32, data: ^void, dataSize: u32, offset: u32): void
|
||||
export extern "rlBindShaderBuffer" func rlBindShaderBuffer(id: u32, index: u32): void
|
||||
export extern "rlReadShaderBuffer" func rlReadShaderBuffer(id: u32, dest: ^void, count: u32, offset: u32): void
|
||||
export extern "rlCopyShaderBuffer" func rlCopyShaderBuffer(destId: u32, srcId: u32, destOffset: u32, srcOffset: u32, count: u32): void
|
||||
export extern "rlGetShaderBufferSize" func rlGetShaderBufferSize(id: u32): u32
|
||||
export extern "rlBindImageTexture" func rlBindImageTexture(id: u32, index: u32, format: i32, readonly: bool): void
|
||||
export extern "rlGetMatrixModelview" func rlGetMatrixModelview(): Matrix
|
||||
export extern "rlGetMatrixProjection" func rlGetMatrixProjection(): Matrix
|
||||
export extern "rlGetMatrixTransform" func rlGetMatrixTransform(): Matrix
|
||||
export extern "rlGetMatrixProjectionStereo" func rlGetMatrixProjectionStereo(eye: i32): Matrix
|
||||
export extern "rlGetMatrixViewOffsetStereo" func rlGetMatrixViewOffsetStereo(eye: i32): Matrix
|
||||
export extern "rlSetMatrixProjection" func rlSetMatrixProjection(proj: Matrix): void
|
||||
export extern "rlSetMatrixModelview" func rlSetMatrixModelview(view: Matrix): void
|
||||
export extern "rlSetMatrixProjectionStereo" func rlSetMatrixProjectionStereo(right: Matrix, left: Matrix): void
|
||||
export extern "rlSetMatrixViewOffsetStereo" func rlSetMatrixViewOffsetStereo(right: Matrix, left: Matrix): void
|
||||
export extern "rlLoadDrawCube" func rlLoadDrawCube(): void
|
||||
export extern "rlLoadDrawQuad" func rlLoadDrawQuad(): void
|
||||
@@ -1,53 +0,0 @@
|
||||
import "raylib"
|
||||
|
||||
module "main"
|
||||
|
||||
extern "main" func main(argc: i64, argv: [?]cstring): i64
|
||||
{
|
||||
raylib::SetConfigFlags(raylib::ConfigFlags.FLAG_VSYNC_HINT | raylib::ConfigFlags.FLAG_WINDOW_RESIZABLE)
|
||||
|
||||
raylib::InitWindow(1600, 900, "Hi from nub-lang")
|
||||
defer raylib::CloseWindow()
|
||||
|
||||
raylib::SetTargetFPS(240)
|
||||
|
||||
let width: i32 = 150
|
||||
let height: i32 = 150
|
||||
|
||||
let x: i32 = raylib::GetScreenWidth() / 2 - (width / 2)
|
||||
let y: i32 = raylib::GetScreenHeight() / 2 - (height / 2)
|
||||
|
||||
let direction: raylib::Vector2 = { x = 1 y = 1 }
|
||||
let speed: f32 = 250
|
||||
|
||||
let bgColor: raylib::Color = { r = 0 g = 0 b = 0 a = 255 }
|
||||
let color: raylib::Color = { r = 255 g = 255 b = 255 a = 255 }
|
||||
|
||||
while !raylib::WindowShouldClose()
|
||||
{
|
||||
if x <= 0 {
|
||||
direction.x = 1
|
||||
} else if x + width >= raylib::GetScreenWidth() {
|
||||
direction.x = -1
|
||||
}
|
||||
|
||||
if y <= 0 {
|
||||
direction.y = 1
|
||||
} else if y + height >= raylib::GetScreenHeight() {
|
||||
direction.y = -1
|
||||
}
|
||||
|
||||
x = x + @floatToInt(i32, direction.x * speed * raylib::GetFrameTime())
|
||||
y = y + @floatToInt(i32, direction.y * speed * raylib::GetFrameTime())
|
||||
|
||||
raylib::BeginDrawing()
|
||||
{
|
||||
raylib::ClearBackground(bgColor)
|
||||
raylib::DrawFPS(10, 10)
|
||||
raylib::DrawRectangle(x, y, width, height, color)
|
||||
}
|
||||
raylib::EndDrawing()
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +0,0 @@
|
||||
Copyright (c) 2013-2024 Ramon Santamaria (@raysan5)
|
||||
|
||||
This software is provided "as-is", without any express or implied warranty. In no event
|
||||
will the authors be held liable for any damages arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose, including commercial
|
||||
applications, and to alter it and redistribute it freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not claim that you
|
||||
wrote the original software. If you use this software in a product, an acknowledgment
|
||||
in the product documentation would be appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be misrepresented
|
||||
as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
@@ -1,150 +0,0 @@
|
||||
<img align="left" style="width:260px" src="https://github.com/raysan5/raylib/blob/master/logo/raylib_logo_animation.gif" width="288px">
|
||||
|
||||
**raylib is a simple and easy-to-use library to enjoy videogames programming.**
|
||||
|
||||
raylib is highly inspired by Borland BGI graphics lib and by XNA framework and it's especially well suited for prototyping, tooling, graphical applications, embedded systems and education.
|
||||
|
||||
*NOTE for ADVENTURERS: raylib is a programming library to enjoy videogames programming; no fancy interface, no visual helpers, no debug button... just coding in the most pure spartan-programmers way.*
|
||||
|
||||
Ready to learn? Jump to [code examples!](https://www.raylib.com/examples.html)
|
||||
|
||||
---
|
||||
|
||||
<br>
|
||||
|
||||
[](https://github.com/raysan5/raylib/releases)
|
||||
[](https://github.com/raysan5/raylib/stargazers)
|
||||
[](https://github.com/raysan5/raylib/commits/master)
|
||||
[](https://github.com/sponsors/raysan5)
|
||||
[](https://repology.org/project/raylib/versions)
|
||||
[](LICENSE)
|
||||
|
||||
[](https://discord.gg/raylib)
|
||||
[](https://www.reddit.com/r/raylib/)
|
||||
[](https://www.youtube.com/c/raylib)
|
||||
[](https://www.twitch.tv/raysan5)
|
||||
|
||||
[](https://github.com/raysan5/raylib/actions?query=workflow%3AWindows)
|
||||
[](https://github.com/raysan5/raylib/actions?query=workflow%3ALinux)
|
||||
[](https://github.com/raysan5/raylib/actions?query=workflow%3AmacOS)
|
||||
[](https://github.com/raysan5/raylib/actions?query=workflow%3AWebAssembly)
|
||||
|
||||
[](https://github.com/raysan5/raylib/actions?query=workflow%3ACMakeBuilds)
|
||||
[](https://github.com/raysan5/raylib/actions/workflows/windows_examples.yml)
|
||||
[](https://github.com/raysan5/raylib/actions/workflows/linux_examples.yml)
|
||||
|
||||
features
|
||||
--------
|
||||
- **NO external dependencies**, all required libraries are [bundled into raylib](https://github.com/raysan5/raylib/tree/master/src/external)
|
||||
- Multiple platforms supported: **Windows, Linux, MacOS, RPI, Android, HTML5... and more!**
|
||||
- Written in plain C code (C99) using PascalCase/camelCase notation
|
||||
- Hardware accelerated with OpenGL (**1.1, 2.1, 3.3, 4.3, ES 2.0, ES 3.0**)
|
||||
- **Unique OpenGL abstraction layer** (usable as standalone module): [rlgl](https://github.com/raysan5/raylib/blob/master/src/rlgl.h)
|
||||
- Multiple **Fonts** formats supported (TTF, OTF, FNT, BDF, sprite fonts)
|
||||
- Multiple texture formats supported, including **compressed formats** (DXT, ETC, ASTC)
|
||||
- **Full 3D support**, including 3D Shapes, Models, Billboards, Heightmaps and more!
|
||||
- Flexible Materials system, supporting classic maps and **PBR maps**
|
||||
- **Animated 3D models** supported (skeletal bones animation) (IQM, M3D, glTF)
|
||||
- Shaders support, including model shaders and **postprocessing** shaders
|
||||
- **Powerful math module** for Vector, Matrix and Quaternion operations: [raymath](https://github.com/raysan5/raylib/blob/master/src/raymath.h)
|
||||
- Audio loading and playing with streaming support (WAV, QOA, OGG, MP3, FLAC, XM, MOD)
|
||||
- **VR stereo rendering** support with configurable HMD device parameters
|
||||
- Huge examples collection with [+140 code examples](https://github.com/raysan5/raylib/tree/master/examples)!
|
||||
- Bindings to [+70 programming languages](https://github.com/raysan5/raylib/blob/master/BINDINGS.md)!
|
||||
- **Free and open source**
|
||||
|
||||
basic example
|
||||
--------------
|
||||
This is a basic raylib example, it creates a window and draws the text `"Congrats! You created your first window!"` in the middle of the screen. Check this example [running live on web here](https://www.raylib.com/examples/core/loader.html?name=core_basic_window).
|
||||
```c
|
||||
#include "raylib.h"
|
||||
|
||||
int main(void)
|
||||
{
|
||||
InitWindow(800, 450, "raylib [core] example - basic window");
|
||||
|
||||
while (!WindowShouldClose())
|
||||
{
|
||||
BeginDrawing();
|
||||
ClearBackground(RAYWHITE);
|
||||
DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY);
|
||||
EndDrawing();
|
||||
}
|
||||
|
||||
CloseWindow();
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
build and installation
|
||||
----------------------
|
||||
|
||||
raylib binary releases for Windows, Linux, macOS, Android and HTML5 are available at the [Github Releases page](https://github.com/raysan5/raylib/releases).
|
||||
|
||||
raylib is also available via multiple package managers on multiple OS distributions.
|
||||
|
||||
#### Installing and building raylib on multiple platforms
|
||||
|
||||
[raylib Wiki](https://github.com/raysan5/raylib/wiki#development-platforms) contains detailed instructions on building and usage on multiple platforms.
|
||||
|
||||
- [Working on Windows](https://github.com/raysan5/raylib/wiki/Working-on-Windows)
|
||||
- [Working on macOS](https://github.com/raysan5/raylib/wiki/Working-on-macOS)
|
||||
- [Working on GNU Linux](https://github.com/raysan5/raylib/wiki/Working-on-GNU-Linux)
|
||||
- [Working on Chrome OS](https://github.com/raysan5/raylib/wiki/Working-on-Chrome-OS)
|
||||
- [Working on FreeBSD](https://github.com/raysan5/raylib/wiki/Working-on-FreeBSD)
|
||||
- [Working on Raspberry Pi](https://github.com/raysan5/raylib/wiki/Working-on-Raspberry-Pi)
|
||||
- [Working for Android](https://github.com/raysan5/raylib/wiki/Working-for-Android)
|
||||
- [Working for Web (HTML5)](https://github.com/raysan5/raylib/wiki/Working-for-Web-(HTML5))
|
||||
- [Working anywhere with CMake](https://github.com/raysan5/raylib/wiki/Working-with-CMake)
|
||||
|
||||
*Note that the Wiki is open for edit, if you find some issues while building raylib for your target platform, feel free to edit the Wiki or open an issue related to it.*
|
||||
|
||||
#### Setup raylib with multiple IDEs
|
||||
|
||||
raylib has been developed on Windows platform using [Notepad++](https://notepad-plus-plus.org/) and [MinGW GCC](https://www.mingw-w64.org/) compiler but it can be used with other IDEs on multiple platforms.
|
||||
|
||||
[Projects directory](https://github.com/raysan5/raylib/tree/master/projects) contains several ready-to-use **project templates** to build raylib and code examples with multiple IDEs.
|
||||
|
||||
*Note that there are lots of IDEs supported, some of the provided templates could require some review, so please, if you find some issue with a template or you think they could be improved, feel free to send a PR or open a related issue.*
|
||||
|
||||
learning and docs
|
||||
------------------
|
||||
|
||||
raylib is designed to be learned using [the examples](https://github.com/raysan5/raylib/tree/master/examples) as the main reference. There is no standard API documentation but there is a [**cheatsheet**](https://www.raylib.com/cheatsheet/cheatsheet.html) containing all the functions available on the library a short description of each one of them, input parameters and result value names should be intuitive enough to understand how each function works.
|
||||
|
||||
Some additional documentation about raylib design can be found in [raylib GitHub Wiki](https://github.com/raysan5/raylib/wiki). Here are the relevant links:
|
||||
|
||||
- [raylib cheatsheet](https://www.raylib.com/cheatsheet/cheatsheet.html)
|
||||
- [raylib architecture](https://github.com/raysan5/raylib/wiki/raylib-architecture)
|
||||
- [raylib library design](https://github.com/raysan5/raylib/wiki)
|
||||
- [raylib examples collection](https://github.com/raysan5/raylib/tree/master/examples)
|
||||
- [raylib games collection](https://github.com/raysan5/raylib-games)
|
||||
|
||||
|
||||
contact and networks
|
||||
---------------------
|
||||
|
||||
raylib is present in several networks and raylib community is growing everyday. If you are using raylib and enjoying it, feel free to join us in any of these networks. The most active network is our [Discord server](https://discord.gg/raylib)! :)
|
||||
|
||||
- Webpage: [https://www.raylib.com](https://www.raylib.com)
|
||||
- Discord: [https://discord.gg/raylib](https://discord.gg/raylib)
|
||||
- Twitter: [https://www.twitter.com/raysan5](https://www.twitter.com/raysan5)
|
||||
- Twitch: [https://www.twitch.tv/raysan5](https://www.twitch.tv/raysan5)
|
||||
- Reddit: [https://www.reddit.com/r/raylib](https://www.reddit.com/r/raylib)
|
||||
- Patreon: [https://www.patreon.com/raylib](https://www.patreon.com/raylib)
|
||||
- YouTube: [https://www.youtube.com/channel/raylib](https://www.youtube.com/c/raylib)
|
||||
|
||||
contributors
|
||||
------------
|
||||
|
||||
<a href="https://github.com/raysan5/raylib/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=raysan5/raylib&max=500&columns=20&anon=1" />
|
||||
</a>
|
||||
|
||||
license
|
||||
-------
|
||||
|
||||
raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, BSD-like license that allows static linking with closed source software. Check [LICENSE](LICENSE) for further details.
|
||||
|
||||
raylib uses internally some libraries for window/graphics/inputs management and also to support different file formats loading, all those libraries are embedded with and are available in [src/external](https://github.com/raysan5/raylib/tree/master/src/external) directory. Check [raylib dependencies LICENSES](https://github.com/raysan5/raylib/wiki/raylib-dependencies) on [raylib Wiki](https://github.com/raysan5/raylib/wiki) for details.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1 +0,0 @@
|
||||
libraylib.so.550
|
||||
Binary file not shown.
@@ -1 +0,0 @@
|
||||
libraylib.so.5.5.0
|
||||
2
vscode-lsp/.gitignore
vendored
2
vscode-lsp/.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
node_modules
|
||||
out
|
||||
@@ -1,5 +0,0 @@
|
||||
import { defineConfig } from '@vscode/test-cli';
|
||||
|
||||
export default defineConfig({
|
||||
files: 'out/test/**/*.test.js',
|
||||
});
|
||||
17
vscode-lsp/.vscode/launch.json
vendored
17
vscode-lsp/.vscode/launch.json
vendored
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Run Extension",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceFolder}"
|
||||
],
|
||||
"outFiles": [
|
||||
"${workspaceFolder}/out/**/*.js"
|
||||
],
|
||||
"preLaunchTask": "${defaultBuildTask}"
|
||||
}
|
||||
]
|
||||
}
|
||||
8
vscode-lsp/.vscode/settings.json
vendored
8
vscode-lsp/.vscode/settings.json
vendored
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"files.exclude": {},
|
||||
"search.exclude": {
|
||||
"out": true,
|
||||
"node_modules": true,
|
||||
},
|
||||
"typescript.tsc.autoDetect": "off"
|
||||
}
|
||||
18
vscode-lsp/.vscode/tasks.json
vendored
18
vscode-lsp/.vscode/tasks.json
vendored
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "watch",
|
||||
"problemMatcher": "$tsc-watch",
|
||||
"isBackground": true,
|
||||
"presentation": {
|
||||
"reveal": "never"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
dotnet publish -c Release ../compiler/NubLang.LSP/NubLang.LSP.csproj
|
||||
cp ../compiler/NubLang.LSP/bin/Release/net9.0/linux-x64/publish/nublsp server/
|
||||
@@ -1,69 +0,0 @@
|
||||
{
|
||||
"comments": {
|
||||
"lineComment": {
|
||||
"comment": "//"
|
||||
},
|
||||
"blockComment": [
|
||||
"/*",
|
||||
"*/"
|
||||
]
|
||||
},
|
||||
"brackets": [
|
||||
[
|
||||
"{",
|
||||
"}"
|
||||
],
|
||||
[
|
||||
"[",
|
||||
"]"
|
||||
],
|
||||
[
|
||||
"(",
|
||||
")"
|
||||
]
|
||||
],
|
||||
"autoClosingPairs": [
|
||||
{
|
||||
"open": "{",
|
||||
"close": "}"
|
||||
},
|
||||
{
|
||||
"open": "[",
|
||||
"close": "]"
|
||||
},
|
||||
{
|
||||
"open": "(",
|
||||
"close": ")"
|
||||
},
|
||||
{
|
||||
"open": "\"",
|
||||
"close": "\""
|
||||
},
|
||||
{
|
||||
"open": "'",
|
||||
"close": "'"
|
||||
}
|
||||
],
|
||||
"surroundingPairs": [
|
||||
[
|
||||
"{",
|
||||
"}"
|
||||
],
|
||||
[
|
||||
"[",
|
||||
"]"
|
||||
],
|
||||
[
|
||||
"(",
|
||||
")"
|
||||
],
|
||||
[
|
||||
"\"",
|
||||
"\""
|
||||
],
|
||||
[
|
||||
"'",
|
||||
"'"
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>generated c soruce</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<pre id="assembly">{{assembly}}</pre>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
139
vscode-lsp/package-lock.json
generated
139
vscode-lsp/package-lock.json
generated
@@ -1,139 +0,0 @@
|
||||
{
|
||||
"name": "nublang",
|
||||
"version": "0.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nublang",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "22.x",
|
||||
"@types/vscode": "^1.105.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.105.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.18.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.18.12.tgz",
|
||||
"integrity": "sha512-BICHQ67iqxQGFSzfCFTT7MRQ5XcBjG5aeKh5Ok38UBbPe5fxTyE+aHFxwVrGyr8GNlqFMLKD1D3P2K/1ks8tog==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/vscode": {
|
||||
"version": "1.105.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.105.0.tgz",
|
||||
"integrity": "sha512-Lotk3CTFlGZN8ray4VxJE7axIyLZZETQJVWi/lYoUVQuqfRxlQhVOfoejsD2V3dVXPSbS15ov5ZyowMAzgUqcw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
|
||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.7.3",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
|
||||
"integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vscode-jsonrpc": {
|
||||
"version": "8.2.0",
|
||||
"resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz",
|
||||
"integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-languageclient": {
|
||||
"version": "9.0.1",
|
||||
"resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz",
|
||||
"integrity": "sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"minimatch": "^5.1.0",
|
||||
"semver": "^7.3.7",
|
||||
"vscode-languageserver-protocol": "3.17.5"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.82.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-languageclient/node_modules/minimatch": {
|
||||
"version": "5.1.6",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz",
|
||||
"integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-languageserver-protocol": {
|
||||
"version": "3.17.5",
|
||||
"resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz",
|
||||
"integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"vscode-jsonrpc": "8.2.0",
|
||||
"vscode-languageserver-types": "3.17.5"
|
||||
}
|
||||
},
|
||||
"node_modules/vscode-languageserver-types": {
|
||||
"version": "3.17.5",
|
||||
"resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz",
|
||||
"integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
{
|
||||
"name": "nub",
|
||||
"displayName": "Nub Language Support",
|
||||
"description": "Language server client for nub lang",
|
||||
"version": "0.0.0",
|
||||
"publisher": "nub31",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.oliste.no/nub31/nub-lang"
|
||||
},
|
||||
"engines": {
|
||||
"vscode": "^1.105.0"
|
||||
},
|
||||
"categories": [
|
||||
"Programming Languages"
|
||||
],
|
||||
"main": "./out/extension.js",
|
||||
"contributes": {
|
||||
"languages": [
|
||||
{
|
||||
"id": "nub",
|
||||
"extensions": [
|
||||
".nub"
|
||||
],
|
||||
"configuration": "./language-configuration.json"
|
||||
}
|
||||
],
|
||||
"grammars": [
|
||||
{
|
||||
"language": "nub",
|
||||
"scopeName": "source.nub",
|
||||
"path": "./syntaxes/nub.tmLanguage.json"
|
||||
}
|
||||
],
|
||||
"commands": [
|
||||
{
|
||||
"command": "nub.openOutput",
|
||||
"title": "Nub: Show Output",
|
||||
"icon": "$(open-preview)"
|
||||
}
|
||||
],
|
||||
"menus": {
|
||||
"editor/title": [
|
||||
{
|
||||
"command": "nub.openOutput",
|
||||
"when": "editorLangId == nub || resourceExtname == .nub",
|
||||
"group": "navigation"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p ./",
|
||||
"watch": "tsc -watch -p ./"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "22.x",
|
||||
"@types/vscode": "^1.105.0",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "^9.0.1"
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import path from 'path';
|
||||
import vscode from 'vscode';
|
||||
import { LanguageClient, TransportKind } from 'vscode-languageclient/node';
|
||||
|
||||
let client: LanguageClient;
|
||||
|
||||
export function activate(context: vscode.ExtensionContext) {
|
||||
const serverExecutable = path.join(context.asAbsolutePath('server'), "nublsp");
|
||||
|
||||
client = new LanguageClient(
|
||||
'nub',
|
||||
'nub lsp client',
|
||||
{
|
||||
run: {
|
||||
command: serverExecutable,
|
||||
transport: TransportKind.stdio,
|
||||
},
|
||||
debug: {
|
||||
command: serverExecutable,
|
||||
transport: TransportKind.stdio,
|
||||
args: ['--debug'],
|
||||
}
|
||||
},
|
||||
{
|
||||
documentSelector: [
|
||||
{ scheme: 'file', language: 'nub' },
|
||||
{ scheme: 'file', pattern: '**/*.nub' }
|
||||
],
|
||||
synchronize: {
|
||||
fileEvents: vscode.workspace.createFileSystemWatcher('**/.clientrc')
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
client.onNotification("nub/output", (params: { path: string, content: string }) => {
|
||||
|
||||
});
|
||||
|
||||
vscode.commands.registerCommand('nub.openOutput', async () => {
|
||||
|
||||
});
|
||||
|
||||
client.start();
|
||||
}
|
||||
|
||||
export function deactivate(): Thenable<void> | undefined {
|
||||
if (!client) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return client.stop();
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
|
||||
"name": "nub",
|
||||
"scopeName": "source.nub",
|
||||
"patterns": [
|
||||
{
|
||||
"include": "#comments"
|
||||
},
|
||||
{
|
||||
"include": "#keywords"
|
||||
},
|
||||
{
|
||||
"include": "#modifiers"
|
||||
},
|
||||
{
|
||||
"include": "#types"
|
||||
},
|
||||
{
|
||||
"include": "#strings"
|
||||
},
|
||||
{
|
||||
"include": "#numbers"
|
||||
},
|
||||
{
|
||||
"include": "#operators"
|
||||
},
|
||||
{
|
||||
"include": "#function-definition"
|
||||
},
|
||||
{
|
||||
"include": "#struct-definition"
|
||||
},
|
||||
{
|
||||
"include": "#function-call"
|
||||
},
|
||||
{
|
||||
"include": "#identifiers"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"comments": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "comment.line.double-slash.nub",
|
||||
"begin": "//",
|
||||
"end": "$"
|
||||
},
|
||||
{
|
||||
"name": "comment.block.nub",
|
||||
"begin": "/\\*",
|
||||
"end": "\\*/"
|
||||
}
|
||||
]
|
||||
},
|
||||
"keywords": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "keyword.control.nub",
|
||||
"match": "\\b(if|else|while|for|in|break|continue|return|let|defer)\\b"
|
||||
},
|
||||
{
|
||||
"name": "keyword.other.nub",
|
||||
"match": "\\b(func|struct|module|import)\\b"
|
||||
}
|
||||
]
|
||||
},
|
||||
"modifiers": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "storage.modifier.nub",
|
||||
"match": "\\b(export|extern)\\b"
|
||||
}
|
||||
]
|
||||
},
|
||||
"types": {
|
||||
"patterns": [
|
||||
{
|
||||
"include": "#function-type"
|
||||
},
|
||||
{
|
||||
"name": "storage.type.primitive.nub",
|
||||
"match": "\\b(i8|i16|i32|i64|u8|u16|u32|u64|f32|f64|bool|string|cstring|void|any)\\b"
|
||||
},
|
||||
{
|
||||
"name": "storage.type.array.nub",
|
||||
"match": "\\[\\]"
|
||||
},
|
||||
{
|
||||
"name": "storage.type.pointer.nub",
|
||||
"match": "\\^"
|
||||
}
|
||||
]
|
||||
},
|
||||
"function-type": {
|
||||
"patterns": [
|
||||
{
|
||||
"begin": "\\b(func)\\s*\\(",
|
||||
"beginCaptures": {
|
||||
"1": {
|
||||
"name": "storage.type.function.nub"
|
||||
}
|
||||
},
|
||||
"end": "(?<=\\))(?:\\s*:\\s*([^\\s,;{}()]+))?",
|
||||
"endCaptures": {
|
||||
"1": {
|
||||
"name": "storage.type.nub"
|
||||
}
|
||||
},
|
||||
"patterns": [
|
||||
{
|
||||
"include": "#function-type-parameters"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"function-type-parameters": {
|
||||
"patterns": [
|
||||
{
|
||||
"match": "\\.\\.\\.",
|
||||
"name": "keyword.operator.variadic.nub"
|
||||
},
|
||||
{
|
||||
"include": "#types"
|
||||
},
|
||||
{
|
||||
"match": ",",
|
||||
"name": "punctuation.separator.nub"
|
||||
}
|
||||
]
|
||||
},
|
||||
"strings": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "string.quoted.double.nub",
|
||||
"begin": "\"",
|
||||
"end": "\"",
|
||||
"patterns": [
|
||||
{
|
||||
"name": "constant.character.escape.nub",
|
||||
"match": "\\\\(n|t|r|\\\\|\"|')"
|
||||
},
|
||||
{
|
||||
"name": "constant.character.escape.nub",
|
||||
"match": "\\\\[0-7]{1,3}"
|
||||
},
|
||||
{
|
||||
"name": "constant.character.escape.nub",
|
||||
"match": "\\\\x[0-9A-Fa-f]{1,2}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "string.quoted.single.nub",
|
||||
"begin": "'",
|
||||
"end": "'",
|
||||
"patterns": [
|
||||
{
|
||||
"name": "constant.character.escape.nub",
|
||||
"match": "\\\\(n|t|r|\\\\|\"|')"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"numbers": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "constant.numeric.float.nub",
|
||||
"match": "\\b\\d+\\.\\d*([eE][+-]?\\d+)?[fF]?\\b"
|
||||
},
|
||||
{
|
||||
"name": "constant.numeric.integer.decimal.nub",
|
||||
"match": "\\b\\d+\\b"
|
||||
},
|
||||
{
|
||||
"name": "constant.numeric.integer.hexadecimal.nub",
|
||||
"match": "\\b0[xX][0-9A-Fa-f]+\\b"
|
||||
},
|
||||
{
|
||||
"name": "constant.numeric.integer.binary.nub",
|
||||
"match": "\\b0[bB][01]+\\b"
|
||||
}
|
||||
]
|
||||
},
|
||||
"operators": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "keyword.operator.assignment.nub",
|
||||
"match": "="
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.comparison.nub",
|
||||
"match": "(==|!=|<=|>=|<|>)"
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.arithmetic.nub",
|
||||
"match": "(\\+|\\-|\\*|/)"
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.logical.nub",
|
||||
"match": "(&&|\\|\\||!)"
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.address.nub",
|
||||
"match": "&"
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.dereference.nub",
|
||||
"match": "\\^"
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.member-access.nub",
|
||||
"match": "\\."
|
||||
},
|
||||
{
|
||||
"name": "keyword.operator.module-access.nub",
|
||||
"match": "::"
|
||||
}
|
||||
]
|
||||
},
|
||||
"function-definition": {
|
||||
"patterns": [
|
||||
{
|
||||
"begin": "\\b(export\\s+|extern\\s+)?(func)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(",
|
||||
"beginCaptures": {
|
||||
"1": {
|
||||
"name": "storage.modifier.nub"
|
||||
},
|
||||
"2": {
|
||||
"name": "keyword.other.nub"
|
||||
},
|
||||
"3": {
|
||||
"name": "entity.name.function.nub"
|
||||
}
|
||||
},
|
||||
"end": "\\)",
|
||||
"patterns": [
|
||||
{
|
||||
"include": "#function-parameters"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"struct-definition": {
|
||||
"patterns": [
|
||||
{
|
||||
"match": "\\b(struct)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\b",
|
||||
"captures": {
|
||||
"1": {
|
||||
"name": "keyword.other.nub"
|
||||
},
|
||||
"2": {
|
||||
"name": "entity.name.type.struct.nub"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"function-parameters": {
|
||||
"patterns": [
|
||||
{
|
||||
"match": "\\.\\.\\.",
|
||||
"name": "keyword.operator.variadic.nub"
|
||||
},
|
||||
{
|
||||
"match": "([a-zA-Z_][a-zA-Z0-9_]*)\\s*:\\s*",
|
||||
"captures": {
|
||||
"1": {
|
||||
"name": "variable.parameter.nub"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"include": "#types"
|
||||
},
|
||||
{
|
||||
"include": "#identifiers"
|
||||
}
|
||||
]
|
||||
},
|
||||
"function-call": {
|
||||
"patterns": [
|
||||
{
|
||||
"match": "([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=\\()",
|
||||
"captures": {
|
||||
"1": {
|
||||
"name": "entity.name.function.call.nub"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"identifiers": {
|
||||
"patterns": [
|
||||
{
|
||||
"name": "variable.other.nub",
|
||||
"match": "\\b[a-zA-Z_][a-zA-Z0-9_]*\\b"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "Node16",
|
||||
"target": "ES2022",
|
||||
"outDir": "out",
|
||||
"lib": [
|
||||
"ES2022"
|
||||
],
|
||||
"sourceMap": true,
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user