Compare commits
4 Commits
dd44e3edc4
...
83255980d7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83255980d7 | ||
|
|
1a1dc1389d | ||
|
|
4210ad878b | ||
|
|
32042d0769 |
@@ -1,7 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using Microsoft.VisualBasic;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
@@ -23,9 +21,9 @@ public class Generator
|
||||
private readonly ModuleGraph moduleGraph;
|
||||
private readonly string? entryPoint;
|
||||
private IndentedTextWriter writer = new();
|
||||
private HashSet<NubType> referencedTypes = new();
|
||||
private readonly Dictionary<string, string> referencedStringLiterals = new();
|
||||
private readonly HashSet<NubType> emittedTypes = new();
|
||||
private readonly HashSet<NubType> referencedTypes = [];
|
||||
private readonly Dictionary<string, string> referencedStringLiterals = [];
|
||||
private readonly HashSet<NubType> emittedTypes = [];
|
||||
private readonly Stack<Scope> scopes = new();
|
||||
private int tmpNameIndex = 0;
|
||||
|
||||
@@ -38,6 +36,7 @@ public class Generator
|
||||
{
|
||||
return {{entryPoint}}();
|
||||
}
|
||||
|
||||
""");
|
||||
|
||||
writer.WriteLine();
|
||||
@@ -94,17 +93,161 @@ public class Generator
|
||||
|
||||
writer = new IndentedTextWriter();
|
||||
|
||||
writer.WriteLine("""
|
||||
#include <float.h>
|
||||
#include <stdarg.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
writer.WriteLine(
|
||||
"""
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
""");
|
||||
typedef struct
|
||||
{
|
||||
char *data;
|
||||
size_t length;
|
||||
uint32_t ref;
|
||||
uint32_t flags;
|
||||
} string;
|
||||
|
||||
typedef uint8_t u8;
|
||||
typedef int8_t i8;
|
||||
|
||||
typedef uint16_t u16;
|
||||
typedef int16_t i16;
|
||||
|
||||
typedef uint32_t u32;
|
||||
typedef int32_t i32;
|
||||
|
||||
typedef uint64_t u64;
|
||||
typedef int64_t i64;
|
||||
|
||||
#define FLAG_STRING_LITERAL 1
|
||||
#define STRING_DEBUG 1
|
||||
|
||||
#if STRING_DEBUG
|
||||
#define STR_DBG(fmt, ...) fprintf(stderr, "[STR] " fmt "\n", ##__VA_ARGS__)
|
||||
#else
|
||||
#define STR_DBG(fmt, ...)
|
||||
#endif
|
||||
|
||||
#if STRING_DEBUG
|
||||
static size_t string_allocs = 0;
|
||||
static size_t string_frees = 0;
|
||||
|
||||
__attribute__((destructor))
|
||||
static void string_debug_report(void)
|
||||
{
|
||||
fprintf(stderr, "[STR] REPORT allocs=%zu frees=%zu leaks=%zu\n", string_allocs, string_frees, string_allocs - string_frees);
|
||||
}
|
||||
#endif
|
||||
|
||||
static inline void string_rc_inc(string *str)
|
||||
{
|
||||
if (str == NULL) {
|
||||
STR_DBG("INC null string");
|
||||
return;
|
||||
}
|
||||
|
||||
if (str->flags & FLAG_STRING_LITERAL)
|
||||
return;
|
||||
|
||||
str->ref += 1;
|
||||
|
||||
STR_DBG("INC: str=%p ref=%u \"%s\"", (void *)str, str->ref, str->data);
|
||||
}
|
||||
|
||||
static inline void string_rc_dec(string *str)
|
||||
{
|
||||
if (str == NULL)
|
||||
{
|
||||
STR_DBG("DEC null string");
|
||||
return;
|
||||
}
|
||||
|
||||
if (str->flags & FLAG_STRING_LITERAL)
|
||||
return;
|
||||
|
||||
if (str->ref == 0)
|
||||
{
|
||||
STR_DBG("ERROR: DEC on zero refcount str=%p", (void *)str);
|
||||
return;
|
||||
}
|
||||
|
||||
str->ref -= 1;
|
||||
|
||||
STR_DBG("DEC: str=%p ref=%u \"%s\"", (void *)str, str->ref, str->data);
|
||||
|
||||
if (str->ref == 0) {
|
||||
STR_DBG("FREE: str=%p data=%p \"%s\"", (void *)str, (void *)str->data, str->data);
|
||||
|
||||
#if STRING_DEBUG
|
||||
string_frees++;
|
||||
#endif
|
||||
|
||||
free(str->data);
|
||||
free(str);
|
||||
}
|
||||
}
|
||||
|
||||
static inline string *string_concat(string *left, string *right)
|
||||
{
|
||||
size_t new_length = left->length + right->length;
|
||||
|
||||
string *result = (string *)malloc(sizeof(string));
|
||||
result->data = (char *)malloc(new_length + 1);
|
||||
|
||||
memcpy(result->data, left->data, left->length);
|
||||
memcpy(result->data + left->length, right->data, right->length);
|
||||
|
||||
result->data[new_length] = '\0';
|
||||
result->length = new_length;
|
||||
result->ref = 1;
|
||||
result->flags = 0;
|
||||
|
||||
#if STRING_DEBUG
|
||||
string_allocs++;
|
||||
STR_DBG("NEW concat: str=%p ref=%u \"%s\"", (void *)result, result->ref, result->data);
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static inline string *string_from_cstr(char *cstr)
|
||||
{
|
||||
size_t len = strlen(cstr);
|
||||
|
||||
string *result = (string *)malloc(sizeof(string));
|
||||
result->data = (char *)malloc(len + 1);
|
||||
|
||||
memcpy(result->data, cstr, len + 1);
|
||||
|
||||
result->length = len;
|
||||
result->ref = 1;
|
||||
result->flags = 0;
|
||||
|
||||
#if STRING_DEBUG
|
||||
string_allocs++;
|
||||
STR_DBG("NEW from_cstr: str=%p ref=%u \"%s\"", (void *)result, result->ref, result->data);
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#define da_append(xs, x) \
|
||||
do \
|
||||
{ \
|
||||
if ((xs)->count >= (xs)->capacity) \
|
||||
{ \
|
||||
if ((xs)->capacity == 0) (xs)->capacity = 256; \
|
||||
else (xs)->capacity *= 2; \
|
||||
(xs)->items = realloc((xs)->items, (xs)->capacity*sizeof(*(xs)->items)); \
|
||||
} \
|
||||
\
|
||||
(xs)->items[(xs)->count++] = (x); \
|
||||
} \
|
||||
while (0)
|
||||
|
||||
"""
|
||||
);
|
||||
|
||||
while (referencedTypes.Count != 0)
|
||||
{
|
||||
@@ -118,9 +261,9 @@ public class Generator
|
||||
writer.WriteLine
|
||||
(
|
||||
$$"""
|
||||
static struct nub_core_string {{name}} = {
|
||||
static string {{name}} = (string){
|
||||
.data = "{{value}}",
|
||||
.length = {{value.Length}},
|
||||
.length = {{Encoding.UTF8.GetByteCount(value)}},
|
||||
.ref = 0,
|
||||
.flags = FLAG_STRING_LITERAL
|
||||
};
|
||||
@@ -143,141 +286,20 @@ public class Generator
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case NubTypeString:
|
||||
case NubTypeArray arrayType:
|
||||
{
|
||||
writer.WriteLine
|
||||
(
|
||||
"""
|
||||
#define FLAG_STRING_LITERAL 1
|
||||
#define STRING_DEBUG 1
|
||||
EmitTypeDefinitionIfNotEmitted(arrayType.ElementType);
|
||||
|
||||
#if STRING_DEBUG
|
||||
#define STR_DBG(fmt, ...) fprintf(stderr, "[STR] " fmt "\n", ##__VA_ARGS__)
|
||||
#else
|
||||
#define STR_DBG(fmt, ...)
|
||||
#endif
|
||||
|
||||
struct nub_core_string
|
||||
writer.WriteLine("typedef struct");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
char *data;
|
||||
size_t length;
|
||||
uint32_t ref;
|
||||
uint32_t flags;
|
||||
};
|
||||
|
||||
#if STRING_DEBUG
|
||||
static size_t nub_core_string_allocs = 0;
|
||||
static size_t nub_core_string_frees = 0;
|
||||
|
||||
__attribute__((destructor))
|
||||
static void string_debug_report(void)
|
||||
{
|
||||
fprintf(stderr, "[STR] REPORT allocs=%zu frees=%zu leaks=%zu\n", nub_core_string_allocs, nub_core_string_frees, nub_core_string_allocs - nub_core_string_frees);
|
||||
writer.WriteLine("size_t count;");
|
||||
writer.WriteLine("size_t capacity;");
|
||||
writer.WriteLine($"{CType(arrayType.ElementType)} *items;");
|
||||
}
|
||||
#endif
|
||||
|
||||
static inline void nub_core_string_rc_inc(struct nub_core_string *string)
|
||||
{
|
||||
if (string == NULL)
|
||||
{
|
||||
STR_DBG("INC null string");
|
||||
return;
|
||||
}
|
||||
|
||||
if (string->flags & FLAG_STRING_LITERAL)
|
||||
return;
|
||||
|
||||
string->ref += 1;
|
||||
|
||||
STR_DBG("INC: str=%p ref=%u \"%s\"", (void*)string, string->ref, string->data);
|
||||
}
|
||||
|
||||
static inline void nub_core_string_rc_dec(struct nub_core_string *string)
|
||||
{
|
||||
if (string == NULL)
|
||||
{
|
||||
STR_DBG("DEC null string");
|
||||
return;
|
||||
}
|
||||
|
||||
if (string->flags & FLAG_STRING_LITERAL)
|
||||
return;
|
||||
|
||||
if (string->ref == 0)
|
||||
{
|
||||
STR_DBG("ERROR: DEC on zero refcount str=%p", (void*)string);
|
||||
return;
|
||||
}
|
||||
|
||||
string->ref -= 1;
|
||||
|
||||
STR_DBG("DEC: str=%p ref=%u \"%s\"", (void*)string, string->ref, string->data);
|
||||
|
||||
if (string->ref == 0)
|
||||
{
|
||||
STR_DBG("FREE: str=%p data=%p \"%s\"", (void*)string, (void*)string->data, string->data);
|
||||
|
||||
char *data_ptr = string->data;
|
||||
struct nub_core_string *str_ptr = string;
|
||||
|
||||
#if STRING_DEBUG
|
||||
nub_core_string_frees++;
|
||||
|
||||
memset(data_ptr, 0xDD, str_ptr->length);
|
||||
memset(str_ptr, 0xDD, sizeof(*str_ptr));
|
||||
#endif
|
||||
|
||||
free(data_ptr);
|
||||
free(str_ptr);
|
||||
}
|
||||
}
|
||||
|
||||
static inline struct nub_core_string *nub_core_string_concat(struct nub_core_string *left, struct nub_core_string *right)
|
||||
{
|
||||
size_t new_length = left->length + right->length;
|
||||
|
||||
struct nub_core_string *result = malloc(sizeof(struct nub_core_string));
|
||||
result->data = malloc(new_length + 1);
|
||||
|
||||
memcpy(result->data, left->data, left->length);
|
||||
memcpy(result->data + left->length, right->data, right->length);
|
||||
|
||||
result->data[new_length] = '\0';
|
||||
result->length = new_length;
|
||||
result->ref = 1;
|
||||
result->flags = 0;
|
||||
|
||||
#if STRING_DEBUG
|
||||
nub_core_string_allocs++;
|
||||
STR_DBG("NEW concat: str=%p ref=%u \"%s\"", (void*)result, result->ref, result->data);
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static inline struct nub_core_string *nub_core_string_from_cstr(char* cstr)
|
||||
{
|
||||
size_t len = strlen(cstr);
|
||||
|
||||
struct nub_core_string *result = malloc(sizeof(struct nub_core_string));
|
||||
result->data = malloc(len + 1);
|
||||
|
||||
memcpy(result->data, cstr, len + 1);
|
||||
|
||||
result->length = len;
|
||||
result->ref = 1;
|
||||
result->flags = 0;
|
||||
|
||||
#if STRING_DEBUG
|
||||
nub_core_string_allocs++;
|
||||
STR_DBG("NEW from_cstr: str=%p ref=%u \"%s\"", (void*)result, result->ref, result->data);
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
"""
|
||||
);
|
||||
writer.WriteLine($"}} {typeNames[arrayType]};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -289,12 +311,10 @@ public class Generator
|
||||
foreach (var field in structInfo.Fields)
|
||||
EmitTypeDefinitionIfNotEmitted(field.Type);
|
||||
|
||||
writer.Write("struct ");
|
||||
|
||||
if (structInfo.Packed)
|
||||
writer.Write("__attribute__((__packed__)) ");
|
||||
|
||||
writer.WriteLine(NameMangler.Mangle(structType.Module, structType.Name, structType));
|
||||
writer.WriteLine("typedef struct");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
@@ -303,7 +323,7 @@ public class Generator
|
||||
writer.WriteLine($"{CType(field.Type, field.Name)};");
|
||||
}
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine($"}} {typeNames[structType]};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
@@ -313,7 +333,7 @@ public class Generator
|
||||
foreach (var field in anonymousStructType.Fields)
|
||||
EmitTypeDefinitionIfNotEmitted(field.Type);
|
||||
|
||||
writer.WriteLine($"struct {NameMangler.Mangle("anonymous", "struct", anonymousStructType)}");
|
||||
writer.WriteLine("typedef struct");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
@@ -322,7 +342,7 @@ public class Generator
|
||||
writer.WriteLine($"{CType(field.Type, field.Name)};");
|
||||
}
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine($"}} {typeNames[anonymousStructType]};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
@@ -340,7 +360,7 @@ public class Generator
|
||||
}
|
||||
}
|
||||
|
||||
writer.WriteLine($"struct {NameMangler.Mangle(enumType.Module, enumType.Name, enumType)}");
|
||||
writer.WriteLine("typedef struct");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
@@ -359,7 +379,7 @@ public class Generator
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine($"}} {typeNames[enumType]};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
@@ -400,6 +420,9 @@ public class Generator
|
||||
case TypedNodeStatementWhile statement:
|
||||
EmitStatementWhile(statement);
|
||||
break;
|
||||
case TypedNodeStatementFor statement:
|
||||
EmitStatementFor(statement);
|
||||
break;
|
||||
case TypedNodeStatementMatch statement:
|
||||
EmitStatementMatch(statement);
|
||||
break;
|
||||
@@ -508,6 +531,21 @@ public class Generator
|
||||
writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private void EmitStatementFor(TypedNodeStatementFor statement)
|
||||
{
|
||||
var index = Tmp();
|
||||
var array = EmitExpression(statement.Array);
|
||||
writer.WriteLine($"for (size_t {index} = 0; {index} < {array}.count; ++{index})");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
var arrayType = (NubTypeArray)statement.Array.Type;
|
||||
writer.WriteLine($"{CType(arrayType.ElementType, statement.VariableName.Ident)} = {array}.items[{index}];");
|
||||
EmitStatement(statement.Body);
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private void EmitStatementMatch(TypedNodeStatementMatch statement)
|
||||
{
|
||||
var target = EmitExpression(statement.Target);
|
||||
@@ -559,10 +597,13 @@ public class Generator
|
||||
TypedNodeExpressionStringLiteral expression => EmitExpressionStringLiteral(expression),
|
||||
TypedNodeExpressionStructLiteral expression => EmitExpressionStructLiteral(expression),
|
||||
TypedNodeExpressionEnumLiteral expression => EmitExpressionEnumLiteral(expression),
|
||||
TypedNodeExpressionArrayLiteral expression => EmitNodeExpressionArrayLiteral(expression),
|
||||
TypedNodeExpressionStringConstructor expression => EmitExpressionStringConstructor(expression),
|
||||
TypedNodeExpressionStructMemberAccess expression => EmitExpressionMemberAccess(expression),
|
||||
TypedNodeExpressionStringLength expression => EmitExpressionStringLength(expression),
|
||||
TypedNodeExpressionStringPointer expression => EmitExpressionStringPointer(expression),
|
||||
TypedNodeExpressionArrayCount expression => EmitExpressionArrayCount(expression),
|
||||
TypedNodeExpressionArrayPointer expression => EmitExpressionArrayPointer(expression),
|
||||
TypedNodeExpressionLocalIdent expression => expression.Name,
|
||||
TypedNodeExpressionGlobalIdent expression => EmitNodeExpressionGlobalIdent(expression),
|
||||
TypedNodeExpressionFuncCall expression => EmitExpressionFuncCall(expression),
|
||||
@@ -580,7 +621,7 @@ public class Generator
|
||||
if (expression.Operation == TypedNodeExpressionBinary.Op.Add && expression.Left.Type is NubTypeString && expression.Right.Type is NubTypeString)
|
||||
{
|
||||
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
|
||||
writer.WriteLine($"{CType(NubTypeString.Instance, name)} = nub_core_string_concat({left}, {right});");
|
||||
writer.WriteLine($"{CType(NubTypeString.Instance, name)} = string_concat({left}, {right});");
|
||||
return name;
|
||||
}
|
||||
|
||||
@@ -685,12 +726,27 @@ public class Generator
|
||||
return name;
|
||||
}
|
||||
|
||||
private string EmitNodeExpressionArrayLiteral(TypedNodeExpressionArrayLiteral expression)
|
||||
{
|
||||
var name = Tmp();
|
||||
|
||||
writer.WriteLine($"{CType(expression.Type, name)} = {{0}};");
|
||||
|
||||
foreach (var value in expression.Values)
|
||||
{
|
||||
var valueName = EmitExpression(value);
|
||||
writer.WriteLine($"da_append(&{name}, {valueName});");
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private string EmitExpressionStringConstructor(TypedNodeExpressionStringConstructor expression)
|
||||
{
|
||||
var name = Tmp();
|
||||
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
|
||||
var value = EmitExpression(expression.Value);
|
||||
writer.WriteLine($"{CType(expression.Type, name)} = nub_core_string_from_cstr({value});");
|
||||
writer.WriteLine($"{CType(expression.Type, name)} = string_from_cstr({value});");
|
||||
return name;
|
||||
}
|
||||
|
||||
@@ -712,6 +768,18 @@ public class Generator
|
||||
return $"{target}->data";
|
||||
}
|
||||
|
||||
private string EmitExpressionArrayCount(TypedNodeExpressionArrayCount expression)
|
||||
{
|
||||
var target = EmitExpression(expression.Target);
|
||||
return $"{target}.count";
|
||||
}
|
||||
|
||||
private string EmitExpressionArrayPointer(TypedNodeExpressionArrayPointer expression)
|
||||
{
|
||||
var target = EmitExpression(expression.Target);
|
||||
return $"{target}.items";
|
||||
}
|
||||
|
||||
private string EmitNodeExpressionGlobalIdent(TypedNodeExpressionGlobalIdent expression)
|
||||
{
|
||||
if (!moduleGraph.TryResolveIdentifier(expression.Module, expression.Name, true, out var info))
|
||||
@@ -738,22 +806,31 @@ public class Generator
|
||||
{
|
||||
NubTypeVoid => "void" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeBool => "bool" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeStruct type => $"struct {NameMangler.Mangle(type.Module, type.Name, type)}" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeAnonymousStruct type => CTypeAnonymousStruct(type, varName),
|
||||
NubTypeEnum type => $"struct {NameMangler.Mangle(type.Module, type.Name, type)}" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeStruct type => CTypeNamed(type, varName),
|
||||
NubTypeAnonymousStruct type => CTypeNamed(type, varName),
|
||||
NubTypeEnum type => CTypeNamed(type, varName),
|
||||
NubTypeEnumVariant type => CType(type.EnumType, varName),
|
||||
NubTypeSInt type => $"int{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeUInt type => $"uint{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeSInt type => $"i{type.Width}" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeUInt type => $"u{type.Width}" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypePointer type => CType(type.To) + (varName != null ? $" *{varName}" : "*"),
|
||||
NubTypeString type => "struct nub_core_string" + (varName != null ? $" *{varName}" : "*"),
|
||||
NubTypeString type => "string" + (varName != null ? $" *{varName}" : "*"),
|
||||
NubTypeFunc type => $"{CType(type.ReturnType)} (*{varName})({string.Join(", ", type.Parameters.Select(p => CType(p)))})",
|
||||
NubTypeArray type => CTypeNamed(type, varName),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node), node, null)
|
||||
};
|
||||
}
|
||||
|
||||
private static string CTypeAnonymousStruct(NubTypeAnonymousStruct type, string? varName)
|
||||
private readonly Dictionary<NubType, string> typeNames = [];
|
||||
|
||||
private string CTypeNamed(NubType type, string? varName)
|
||||
{
|
||||
return $"struct {NameMangler.Mangle("anonymous", "struct", type)}{(varName != null ? $" {varName}" : "")}";
|
||||
if (!typeNames.TryGetValue(type, out var name))
|
||||
{
|
||||
name = Tmp();
|
||||
typeNames[type] = name;
|
||||
}
|
||||
|
||||
return $"{name}{(varName != null ? $" {varName}" : "")}";
|
||||
}
|
||||
|
||||
private string Tmp()
|
||||
@@ -788,7 +865,7 @@ public class Generator
|
||||
{
|
||||
case NubTypeString:
|
||||
{
|
||||
writer.WriteLine($"nub_core_string_rc_inc({value});");
|
||||
writer.WriteLine($"string_rc_inc({value});");
|
||||
break;
|
||||
}
|
||||
case NubTypeStruct structType:
|
||||
@@ -859,7 +936,7 @@ public class Generator
|
||||
{
|
||||
case NubTypeString:
|
||||
{
|
||||
writer.WriteLine($"nub_core_string_rc_dec({value});");
|
||||
writer.WriteLine($"string_rc_dec({value});");
|
||||
break;
|
||||
}
|
||||
case NubTypeStruct structType:
|
||||
|
||||
@@ -211,6 +211,7 @@ public class ModuleGraph
|
||||
NodeTypeUInt type => NubTypeUInt.Get(type.Width),
|
||||
NodeTypeString => NubTypeString.Instance,
|
||||
NodeTypeVoid => NubTypeVoid.Instance,
|
||||
NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType, currentModule)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -256,6 +256,28 @@ public class NubTypeFunc : NubType
|
||||
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)
|
||||
@@ -355,6 +377,12 @@ public class TypeEncoder
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeArray a:
|
||||
sb.Append("A(");
|
||||
EncodeType(sb, a.ElementType);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new NotSupportedException(type.GetType().Name);
|
||||
}
|
||||
@@ -396,6 +424,7 @@ public class TypeDecoder
|
||||
'F' => DecodeFunc(),
|
||||
'T' => DecodeStruct(),
|
||||
'E' => DecodeEnum(),
|
||||
'A' => DecodeArray(),
|
||||
_ => throw new Exception($"'{start}' is not a valid start to a type")
|
||||
};
|
||||
}
|
||||
@@ -531,6 +560,14 @@ public class TypeDecoder
|
||||
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)
|
||||
|
||||
@@ -263,8 +263,17 @@ public class Parser
|
||||
if (TryExpectKeyword(Keyword.While))
|
||||
{
|
||||
var condition = ParseExpression();
|
||||
var thenBlock = ParseStatement();
|
||||
return new NodeStatementWhile(TokensFrom(startIndex), condition, thenBlock);
|
||||
var block = ParseStatement();
|
||||
return new NodeStatementWhile(TokensFrom(startIndex), condition, block);
|
||||
}
|
||||
|
||||
if (TryExpectKeyword(Keyword.For))
|
||||
{
|
||||
var variableName = ExpectIdent();
|
||||
ExpectKeyword(Keyword.In);
|
||||
var array = ParseExpression();
|
||||
var block = ParseStatement();
|
||||
return new NodeStatementFor(TokensFrom(startIndex), variableName, array, block);
|
||||
}
|
||||
|
||||
if (TryExpectKeyword(Keyword.Match))
|
||||
@@ -363,6 +372,19 @@ public class Parser
|
||||
var target = ParseExpression();
|
||||
expr = new NodeExpressionUnary(TokensFrom(startIndex), target, NodeExpressionUnary.Op.Negate);
|
||||
}
|
||||
else if (TryExpectSymbol(Symbol.OpenSquare))
|
||||
{
|
||||
var values = new List<NodeExpression>();
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseSquare))
|
||||
{
|
||||
var value = ParseExpression();
|
||||
values.Add(value);
|
||||
TryExpectSymbol(Symbol.Comma);
|
||||
}
|
||||
|
||||
expr = new NodeExpressionArrayLiteral(TokensFrom(startIndex), values);
|
||||
}
|
||||
else if (TryExpectSymbol(Symbol.OpenCurly))
|
||||
{
|
||||
var initializers = new List<NodeExpressionStructLiteral.Initializer>();
|
||||
@@ -467,7 +489,10 @@ public class Parser
|
||||
var parameters = new List<NodeExpression>();
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseParen))
|
||||
{
|
||||
parameters.Add(ParseExpression());
|
||||
TryExpectSymbol(Symbol.Comma);
|
||||
}
|
||||
|
||||
expr = new NodeExpressionFuncCall(TokensFrom(startIndex), expr, parameters);
|
||||
}
|
||||
@@ -521,6 +546,13 @@ public class Parser
|
||||
return new NodeTypeAnonymousStruct(TokensFrom(startIndex), fields);
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.OpenSquare))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseSquare);
|
||||
var elementType = ParseType();
|
||||
return new NodeTypeArray(TokensFrom(startIndex), elementType);
|
||||
}
|
||||
|
||||
if (TryExpectIdent(out var ident))
|
||||
{
|
||||
switch (ident.Ident)
|
||||
@@ -883,6 +915,13 @@ public class NodeStatementWhile(List<Token> tokens, NodeExpression condition, No
|
||||
public NodeStatement Body { get; } = body;
|
||||
}
|
||||
|
||||
public class NodeStatementFor(List<Token> tokens, TokenIdent variableName, NodeExpression array, NodeStatement body) : NodeStatement(tokens)
|
||||
{
|
||||
public TokenIdent VariableName { get; } = variableName;
|
||||
public NodeExpression Array { get; } = array;
|
||||
public NodeStatement Body { get; } = body;
|
||||
}
|
||||
|
||||
public class NodeStatementMatch(List<Token> tokens, NodeExpression target, List<NodeStatementMatch.Case> cases) : NodeStatement(tokens)
|
||||
{
|
||||
public NodeExpression Target { get; } = target;
|
||||
@@ -931,6 +970,11 @@ public class NodeExpressionEnumLiteral(List<Token> tokens, NodeTypeNamed type, N
|
||||
public NodeExpression? Value { get; } = value;
|
||||
}
|
||||
|
||||
public class NodeExpressionArrayLiteral(List<Token> tokens, List<NodeExpression> values) : NodeExpression(tokens)
|
||||
{
|
||||
public List<NodeExpression> Values { get; } = values;
|
||||
}
|
||||
|
||||
public class NodeExpressionStringConstructor(List<Token> tokens, NodeExpression value) : NodeExpression(tokens)
|
||||
{
|
||||
public NodeExpression Value { get; } = value;
|
||||
@@ -1032,6 +1076,11 @@ public class NodeTypeAnonymousStruct(List<Token> tokens, List<NodeTypeAnonymousS
|
||||
}
|
||||
}
|
||||
|
||||
public class NodeTypeArray(List<Token> tokens, NodeType elementType) : NodeType(tokens)
|
||||
{
|
||||
public NodeType ElementType { get; } = elementType;
|
||||
}
|
||||
|
||||
public class NodeTypePointer(List<Token> tokens, NodeType to) : NodeType(tokens)
|
||||
{
|
||||
public NodeType To { get; } = to;
|
||||
|
||||
@@ -144,12 +144,6 @@ if (!compileLib)
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (entryPointType.Parameters.Any())
|
||||
{
|
||||
DiagnosticFormatter.Print(Diagnostic.Error($"Entrypoint must not take any parameters").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
entryPoint = info.MangledName;
|
||||
}
|
||||
|
||||
|
||||
@@ -203,6 +203,16 @@ public class Tokenizer
|
||||
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();
|
||||
@@ -395,6 +405,8 @@ public class Tokenizer
|
||||
"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),
|
||||
@@ -497,6 +509,8 @@ public enum Symbol
|
||||
CloseCurly,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
OpenSquare,
|
||||
CloseSquare,
|
||||
Comma,
|
||||
Period,
|
||||
Colon,
|
||||
@@ -545,6 +559,8 @@ public enum Keyword
|
||||
If,
|
||||
Else,
|
||||
While,
|
||||
For,
|
||||
In,
|
||||
Return,
|
||||
Module,
|
||||
Export,
|
||||
@@ -566,6 +582,8 @@ public static class TokenExtensions
|
||||
Symbol.CloseCurly => "}",
|
||||
Symbol.OpenParen => "(",
|
||||
Symbol.CloseParen => ")",
|
||||
Symbol.OpenSquare => "[",
|
||||
Symbol.CloseSquare => "]",
|
||||
Symbol.Comma => ",",
|
||||
Symbol.Period => ".",
|
||||
Symbol.Colon => ":",
|
||||
@@ -613,6 +631,8 @@ public static class TokenExtensions
|
||||
Keyword.If => "if",
|
||||
Keyword.Else => "else",
|
||||
Keyword.While => "while",
|
||||
Keyword.For => "for",
|
||||
Keyword.In => "in",
|
||||
Keyword.Return => "return",
|
||||
Keyword.Module => "module",
|
||||
Keyword.Export => "export",
|
||||
|
||||
@@ -99,6 +99,7 @@ public class TypeChecker
|
||||
NodeStatementReturn statement => CheckStatementReturn(statement),
|
||||
NodeStatementVariableDeclaration statement => CheckStatementVariableDeclaration(statement),
|
||||
NodeStatementWhile statement => CheckStatementWhile(statement),
|
||||
NodeStatementFor statement => CheckStatementFor(statement),
|
||||
NodeStatementMatch statement => CheckStatementMatch(statement),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
@@ -204,6 +205,22 @@ public class TypeChecker
|
||||
}
|
||||
}
|
||||
|
||||
private TypedNodeStatementFor CheckStatementFor(NodeStatementFor statement)
|
||||
{
|
||||
var array = CheckExpression(statement.Array, null);
|
||||
if (array.Type is not NubTypeArray arrayType)
|
||||
throw BasicError($"Cannot iterate over non-array type '{array.Type}'", statement.Array);
|
||||
|
||||
TypedNodeStatement body;
|
||||
using (EnterScope())
|
||||
{
|
||||
DeclareLocalIdentifier(statement.VariableName, arrayType.ElementType);
|
||||
body = CheckStatement(statement.Body);
|
||||
}
|
||||
|
||||
return new TypedNodeStatementFor(statement.Tokens, statement.VariableName, array, body);
|
||||
}
|
||||
|
||||
private TypedNodeStatementMatch CheckStatementMatch(NodeStatementMatch statement)
|
||||
{
|
||||
var target = CheckExpression(statement.Target, null);
|
||||
@@ -264,6 +281,7 @@ public class TypeChecker
|
||||
NodeExpressionStructLiteral expression => CheckExpressionStructLiteral(expression, expectedType),
|
||||
NodeExpressionEnumLiteral expression => CheckExpressionEnumLiteral(expression, expectedType),
|
||||
NodeExpressionStringConstructor expression => CheckExpressionStringConstructor(expression, expectedType),
|
||||
NodeExpressionArrayLiteral expression => CheckExpressionArrayLiteral(expression, expectedType),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
}
|
||||
@@ -478,7 +496,19 @@ public class TypeChecker
|
||||
case "ptr":
|
||||
return new TypedNodeExpressionStringPointer(expression.Tokens, NubTypePointer.Get(NubTypeUInt.Get(8)), target);
|
||||
default:
|
||||
throw BasicError($"'{expression.Name.Ident}' is not a member of type string", expression.Name);
|
||||
throw BasicError($"'{expression.Name.Ident}' is not a member of type {stringType}", expression.Name);
|
||||
}
|
||||
}
|
||||
case NubTypeArray arrayType:
|
||||
{
|
||||
switch (expression.Name.Ident)
|
||||
{
|
||||
case "count":
|
||||
return new TypedNodeExpressionArrayCount(expression.Tokens, NubTypeUInt.Get(64), target);
|
||||
case "ptr":
|
||||
return new TypedNodeExpressionArrayPointer(expression.Tokens, NubTypePointer.Get(arrayType.ElementType), target);
|
||||
default:
|
||||
throw BasicError($"'{expression.Name.Ident}' is not a member of type {arrayType}", expression.Name);
|
||||
}
|
||||
}
|
||||
case NubTypeStruct structType:
|
||||
@@ -663,6 +693,31 @@ public class TypeChecker
|
||||
return new TypedNodeExpressionStringConstructor(expression.Tokens, NubTypeString.Instance, value);
|
||||
}
|
||||
|
||||
private TypedNodeExpressionArrayLiteral CheckExpressionArrayLiteral(NodeExpressionArrayLiteral expression, NubType? expectedType)
|
||||
{
|
||||
NubType? elementType = null;
|
||||
if (expectedType is NubTypeArray arrayType)
|
||||
elementType = arrayType.ElementType;
|
||||
|
||||
var values = new List<TypedNodeExpression>();
|
||||
|
||||
foreach (var value in expression.Values)
|
||||
{
|
||||
var checkedValue = CheckExpression(value, elementType);
|
||||
elementType ??= checkedValue.Type;
|
||||
|
||||
if (!checkedValue.Type.IsAssignableTo(elementType))
|
||||
throw BasicError($"Type '{checkedValue.Type}' is not assignable to type of element '{elementType}'", checkedValue);
|
||||
|
||||
values.Add(checkedValue);
|
||||
}
|
||||
|
||||
if (elementType is null)
|
||||
throw BasicError("Unable to infer type of array element", expression);
|
||||
|
||||
return new TypedNodeExpressionArrayLiteral(expression.Tokens, NubTypeArray.Get(elementType), values);
|
||||
}
|
||||
|
||||
private NubType ResolveType(NodeType node)
|
||||
{
|
||||
return node switch
|
||||
@@ -676,6 +731,7 @@ public class TypeChecker
|
||||
NodeTypeUInt type => NubTypeUInt.Get(type.Width),
|
||||
NodeTypeString => NubTypeString.Instance,
|
||||
NodeTypeVoid => NubTypeVoid.Instance,
|
||||
NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
}
|
||||
@@ -895,6 +951,13 @@ public class TypedNodeStatementWhile(List<Token> tokens, TypedNodeExpression con
|
||||
public TypedNodeStatement Body { get; } = body;
|
||||
}
|
||||
|
||||
public class TypedNodeStatementFor(List<Token> tokens, TokenIdent variableName, TypedNodeExpression array, TypedNodeStatement body) : TypedNodeStatement(tokens)
|
||||
{
|
||||
public TokenIdent VariableName { get; } = variableName;
|
||||
public TypedNodeExpression Array { get; } = array;
|
||||
public TypedNodeStatement Body { get; } = body;
|
||||
}
|
||||
|
||||
public class TypedNodeStatementMatch(List<Token> tokens, TypedNodeExpression target, List<TypedNodeStatementMatch.Case> cases) : TypedNodeStatement(tokens)
|
||||
{
|
||||
public TypedNodeExpression Target { get; } = target;
|
||||
@@ -949,6 +1012,11 @@ public class TypedNodeExpressionStringConstructor(List<Token> tokens, NubType ty
|
||||
public TypedNodeExpression Value { get; } = value;
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionArrayLiteral(List<Token> tokens, NubType type, List<TypedNodeExpression> values) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
public List<TypedNodeExpression> Values { get; } = values;
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionStructMemberAccess(List<Token> tokens, NubType type, TypedNodeExpression target, TokenIdent name) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
public TypedNodeExpression Target { get; } = target;
|
||||
@@ -965,6 +1033,16 @@ public class TypedNodeExpressionStringPointer(List<Token> tokens, NubType type,
|
||||
public TypedNodeExpression Target { get; } = target;
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionArrayCount(List<Token> tokens, NubType type, TypedNodeExpression target) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
public TypedNodeExpression Target { get; } = target;
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionArrayPointer(List<Token> tokens, NubType type, TypedNodeExpression target) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
public TypedNodeExpression Target { get; } = target;
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionFuncCall(List<Token> tokens, NubType type, TypedNodeExpression target, List<TypedNodeExpression> parameters) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
public TypedNodeExpression Target { get; } = target;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
module core
|
||||
|
||||
export func print(text: string) {
|
||||
sys::write(0 text.ptr text.length)
|
||||
sys::write(0, text.ptr, text.length)
|
||||
}
|
||||
|
||||
export func println(text: string) {
|
||||
|
||||
@@ -11,27 +11,11 @@ enum Message {
|
||||
}
|
||||
|
||||
func main(): i32 {
|
||||
core::println("Hello, world!")
|
||||
core::println("Hello" + "World")
|
||||
let names = ["a", "b", "c", "d"]
|
||||
|
||||
let message = getMessage()
|
||||
|
||||
let newStr = new string("cstring".ptr)
|
||||
|
||||
core::println(newStr)
|
||||
|
||||
match message {
|
||||
Quit {
|
||||
core::println("quit")
|
||||
}
|
||||
Say msg {
|
||||
core::println(msg)
|
||||
}
|
||||
for name in names {
|
||||
core::println(name)
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func getMessage(): Message {
|
||||
return new Message::Say("test")
|
||||
}
|
||||
Reference in New Issue
Block a user