Compare commits

..

10 Commits

Author SHA1 Message Date
nub31
aa5a494d39 Add generic unt/uint 2026-03-16 21:13:49 +01:00
nub31
bc65c3f4fd ... 2026-03-16 18:10:03 +01:00
nub31
bdeb2c4d73 Update build 2026-03-16 17:05:24 +01:00
nub31
48760dcdda ... 2026-03-16 16:53:48 +01:00
nub31
63d0eb660b CType -> TypeName 2026-03-16 16:04:43 +01:00
nub31
918d25f8c8 perhaps 2026-03-15 01:38:59 +01:00
nub31
6e631ba1ba STR -> RC for report 2026-03-12 16:07:40 +01:00
nub31
832184053f better rc 2026-03-12 15:42:44 +01:00
nub31
2ab20652f8 ... 2026-03-10 17:53:42 +01:00
nub31
6507624e90 .. 2026-03-10 17:09:07 +01:00
10 changed files with 381 additions and 285 deletions

View File

@@ -17,11 +17,119 @@ public class Generator
this.entryPoint = entryPoint; this.entryPoint = entryPoint;
} }
const string NUB_H_CONTENTS =
"""
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
static inline void *nub_alloc(size_t size)
{
void *mem = malloc(size);
if (mem == NULL)
{
puts("Out of memory");
exit(1);
}
return mem;
}
typedef struct
{
char *data;
size_t length;
size_t ref;
uint32_t flags;
} string;
typedef string *string_ptr;
#define FLAG_STRING_LITERAL 1
static inline void string_rc_inc(string_ptr str)
{
if (str == NULL)
return;
if (str->flags & FLAG_STRING_LITERAL)
return;
str->ref += 1;
}
static inline void string_rc_dec(string_ptr str)
{
if (str == NULL)
return;
if (str->flags & FLAG_STRING_LITERAL)
return;
if (str->ref == 0)
return;
str->ref -= 1;
if (str->ref == 0)
{
free(str->data);
free(str);
}
}
static inline string_ptr string_concat(string_ptr left, string_ptr right)
{
size_t new_length = left->length + right->length;
string_ptr result = (string_ptr)nub_alloc(sizeof(string));
result->data = (char*)nub_alloc(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;
return result;
}
static inline string_ptr string_from_cstr(char *cstr)
{
size_t len = strlen(cstr);
string_ptr result = (string_ptr)nub_alloc(sizeof(string));
result->data = (char*)nub_alloc(len + 1);
memcpy(result->data, cstr, len + 1);
result->length = len;
result->ref = 1;
result->flags = 0;
return result;
}
#define da_append(xs, x) \
do \
{ \
if ((xs)->count >= (xs)->capacity) \
{ \
(xs)->capacity *= 2; \
(xs)->items = realloc((xs)->items, (xs)->capacity * sizeof(*(xs)->items)); \
} \
(xs)->items[(xs)->count++] = (x); \
} while (0)
""";
private readonly List<TypedNodeDefinitionFunc> functions; private readonly List<TypedNodeDefinitionFunc> functions;
private readonly ModuleGraph moduleGraph; private readonly ModuleGraph moduleGraph;
private readonly string? entryPoint; private readonly string? entryPoint;
private IndentedTextWriter writer = new(); private IndentedTextWriter writer = new();
private readonly HashSet<NubType> referencedTypes = [];
private readonly Dictionary<string, string> referencedStringLiterals = []; private readonly Dictionary<string, string> referencedStringLiterals = [];
private readonly HashSet<NubType> emittedTypes = []; private readonly HashSet<NubType> emittedTypes = [];
private readonly Stack<Scope> scopes = new(); private readonly Stack<Scope> scopes = new();
@@ -29,16 +137,18 @@ public class Generator
private string Emit() private string Emit()
{ {
var outPath = ".build";
var fileName = "out.c";
if (entryPoint != null) if (entryPoint != null)
{ {
writer.WriteLine($$""" writer.WriteLine("int main(int argc, char *argv[])");
int main(int argc, char *argv[]) writer.WriteLine("{");
{ using (writer.Indent())
return {{entryPoint}}(); {
} writer.WriteLine($"return {entryPoint}();");
}
"""); writer.WriteLine("}");
writer.WriteLine(); writer.WriteLine();
} }
@@ -47,14 +157,12 @@ public class Generator
if (!moduleGraph.TryResolveIdentifier(function.Module, function.Name.Ident, true, out var info)) if (!moduleGraph.TryResolveIdentifier(function.Module, function.Name.Ident, true, out var info))
throw new UnreachableException($"Module graph does not have info about the function {function.Module}::{function.Name.Ident}. This should have been caught earlier"); throw new UnreachableException($"Module graph does not have info about the function {function.Module}::{function.Name.Ident}. This should have been caught earlier");
if (info.Source == Module.DefinitionSource.Imported || info.Extern) if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported)
writer.Write("extern ");
else if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported)
writer.Write("static "); writer.Write("static ");
var parameters = function.Parameters.Select(x => CType(x.Type, x.Name.Ident)); var parameters = function.Parameters.Select(x => $"{TypeName(x.Type)} {x.Name.Ident}");
writer.WriteLine($"{CType(function.ReturnType, info.MangledName)}({string.Join(", ", parameters)})"); writer.WriteLine($"{TypeName(function.ReturnType)} {info.MangledName}({string.Join(", ", parameters)})");
writer.WriteLine("{"); writer.WriteLine("{");
using (writer.Indent()) using (writer.Indent())
{ {
@@ -66,7 +174,7 @@ public class Generator
writer.WriteLine(); writer.WriteLine();
} }
var implementations = writer.ToString(); var definitions = writer.ToString();
writer = new IndentedTextWriter(); writer = new IndentedTextWriter();
@@ -82,180 +190,15 @@ public class Generator
writer.Write("static "); writer.Write("static ");
if (info.Type is NubTypeFunc fn) if (info.Type is NubTypeFunc fn)
writer.WriteLine($"{CType(fn.ReturnType, info.MangledName)}({string.Join(", ", fn.Parameters.Select(p => CType(p)))});"); writer.WriteLine($"{TypeName(fn.ReturnType)} {info.MangledName}({string.Join(", ", fn.Parameters.Select(TypeName))});");
else else
writer.WriteLine($"{CType(info.Type, info.MangledName)};"); writer.WriteLine($"{TypeName(info.Type)} {info.MangledName};");
writer.WriteLine();
} }
} }
} }
var declarations = writer.ToString();
writer = new IndentedTextWriter();
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)
{
var type = referencedTypes.ElementAt(0);
EmitTypeDefinitionIfNotEmitted(type);
referencedTypes.Remove(type);
}
foreach (var (name, value) in referencedStringLiterals) foreach (var (name, value) in referencedStringLiterals)
{ {
writer.WriteLine writer.WriteLine
@@ -272,9 +215,38 @@ static inline string *string_from_cstr(char *cstr)
); );
} }
var header = writer.ToString(); var declarations = writer.ToString();
return $"{header}\n{declarations}\n{implementations}"; writer = new IndentedTextWriter();
while (emittedTypes.Count != typeNames.Count)
{
var nextTypes = typeNames.Keys.ToArray();
foreach (var type in nextTypes)
{
EmitTypeDefinitionIfNotEmitted(type);
}
}
var types = writer.ToString();
var sb = new StringBuilder();
sb.AppendLine("#include \"nub.h\"");
sb.AppendLine();
sb.AppendLine(types);
sb.AppendLine(declarations);
sb.AppendLine(definitions);
Directory.CreateDirectory(outPath);
var filePath = Path.Combine(outPath, fileName);
File.WriteAllText(Path.Combine(outPath, "nub.h"), NUB_H_CONTENTS);
File.WriteAllText(filePath, sb.ToString());
return filePath;
} }
private void EmitTypeDefinitionIfNotEmitted(NubType type) private void EmitTypeDefinitionIfNotEmitted(NubType type)
@@ -284,25 +256,10 @@ static inline string *string_from_cstr(char *cstr)
emittedTypes.Add(type); emittedTypes.Add(type);
var name = TypeName(type);
switch (type) switch (type)
{ {
case NubTypeArray arrayType:
{
EmitTypeDefinitionIfNotEmitted(arrayType.ElementType);
writer.WriteLine("typedef struct");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("size_t count;");
writer.WriteLine("size_t capacity;");
writer.WriteLine($"{CType(arrayType.ElementType)} *items;");
}
writer.WriteLine($"}} {typeNames[arrayType]};");
writer.WriteLine();
break;
}
case NubTypeStruct structType: case NubTypeStruct structType:
{ {
if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo) if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo)
@@ -320,10 +277,10 @@ static inline string *string_from_cstr(char *cstr)
{ {
foreach (var field in structInfo.Fields) foreach (var field in structInfo.Fields)
{ {
writer.WriteLine($"{CType(field.Type, field.Name)};"); writer.WriteLine($"{TypeName(field.Type)} {field.Name};");
} }
} }
writer.WriteLine($"}} {typeNames[structType]};"); writer.WriteLine($"}} {name};");
writer.WriteLine(); writer.WriteLine();
break; break;
@@ -339,10 +296,10 @@ static inline string *string_from_cstr(char *cstr)
{ {
foreach (var field in anonymousStructType.Fields) foreach (var field in anonymousStructType.Fields)
{ {
writer.WriteLine($"{CType(field.Type, field.Name)};"); writer.WriteLine($"{TypeName(field.Type)} {field.Name};");
} }
} }
writer.WriteLine($"}} {typeNames[anonymousStructType]};"); writer.WriteLine($"}} {name};");
writer.WriteLine(); writer.WriteLine();
break; break;
@@ -373,13 +330,13 @@ static inline string *string_from_cstr(char *cstr)
{ {
if (variant.Type is not null) if (variant.Type is not null)
{ {
writer.WriteLine($"{CType(variant.Type, variant.Name)};"); writer.WriteLine($"{TypeName(variant.Type)} {variant.Name};");
} }
} }
} }
writer.WriteLine("};"); writer.WriteLine("};");
} }
writer.WriteLine($"}} {typeNames[enumType]};"); writer.WriteLine($"}} {name};");
writer.WriteLine(); writer.WriteLine();
break; break;
@@ -387,6 +344,98 @@ static inline string *string_from_cstr(char *cstr)
case NubTypeEnumVariant variantType: case NubTypeEnumVariant variantType:
{ {
EmitTypeDefinitionIfNotEmitted(variantType.EnumType); EmitTypeDefinitionIfNotEmitted(variantType.EnumType);
break;
}
case NubTypePointer pointerType:
{
EmitTypeDefinitionIfNotEmitted(pointerType.To);
writer.WriteLine($"typedef {TypeName(pointerType.To)} *{name};");
break;
}
case NubTypeFunc funcType:
{
EmitTypeDefinitionIfNotEmitted(funcType.ReturnType);
foreach (var parameterType in funcType.Parameters)
EmitTypeDefinitionIfNotEmitted(parameterType);
writer.WriteLine($"typedef {TypeName(funcType.ReturnType)} (*)({string.Join(", ", funcType.Parameters.Select(TypeName))}) {name};");
break;
}
case NubTypeArray arrayType:
{
EmitTypeDefinitionIfNotEmitted(arrayType.ElementType);
var backingName = Tmp();
writer.WriteLine("typedef struct");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("size_t count;");
writer.WriteLine("size_t capacity;");
writer.WriteLine($"{TypeName(arrayType.ElementType)} *items;");
writer.WriteLine("uint32_t ref;");
}
writer.WriteLine($"}} {backingName};");
writer.WriteLine();
writer.WriteLine($"typedef {backingName} *{name};");
writer.WriteLine();
writer.WriteLine($"static inline void {name}_rc_inc({name} array)");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("if (array == NULL) return;");
writer.WriteLine("array->ref += 1;");
}
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine($"static inline void {name}_rc_dec({name} array)");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("if (array == NULL) return;");
writer.WriteLine("if (array->ref == 0) return;");
writer.WriteLine();
writer.WriteLine("array->ref -= 1;");
writer.WriteLine();
writer.WriteLine("if (array->ref == 0)");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("for (size_t i = 0; i < array->count; ++i)");
writer.WriteLine("{");
using (writer.Indent())
{
EmitCopyDestructor("array->items[i]", arrayType.ElementType);
}
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("free(array->items);");
writer.WriteLine("free(array);");
}
writer.WriteLine("}");
}
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine($"static inline {name} {name}_make()");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine($"{name} array = ({name})nub_alloc(sizeof({backingName}));");
writer.WriteLine("array->ref = 1;");
writer.WriteLine("array->count = 0;");
writer.WriteLine("array->capacity = 10;");
writer.WriteLine($"array->items = ({TypeName(arrayType.ElementType)}*)nub_alloc(sizeof({TypeName(arrayType.ElementType)}) * array->capacity);");
writer.WriteLine("return array;");
}
writer.WriteLine("}");
writer.WriteLine();
break; break;
} }
} }
@@ -472,7 +521,7 @@ static inline string *string_from_cstr(char *cstr)
{ {
var value = EmitExpression(statement.Value); var value = EmitExpression(statement.Value);
EmitCopyConstructor(value, statement.Value.Type); EmitCopyConstructor(value, statement.Value.Type);
writer.WriteLine($"{CType(statement.Type, statement.Name.Ident)} = {value};"); writer.WriteLine($"{TypeName(statement.Type)} {statement.Name.Ident} = {value};");
scopes.Peek().DeconstructableNames.Add((statement.Name.Ident, statement.Type)); scopes.Peek().DeconstructableNames.Add((statement.Name.Ident, statement.Type));
} }
@@ -535,12 +584,12 @@ static inline string *string_from_cstr(char *cstr)
{ {
var index = Tmp(); var index = Tmp();
var array = EmitExpression(statement.Array); var array = EmitExpression(statement.Array);
writer.WriteLine($"for (size_t {index} = 0; {index} < {array}.count; ++{index})"); writer.WriteLine($"for (size_t {index} = 0; {index} < {array}->count; ++{index})");
writer.WriteLine("{"); writer.WriteLine("{");
using (writer.Indent()) using (writer.Indent())
{ {
var arrayType = (NubTypeArray)statement.Array.Type; var arrayType = (NubTypeArray)statement.Array.Type;
writer.WriteLine($"{CType(arrayType.ElementType, statement.VariableName.Ident)} = {array}.items[{index}];"); writer.WriteLine($"{TypeName(arrayType.ElementType)} {statement.VariableName.Ident} = {array}->items[{index}];");
EmitStatement(statement.Body); EmitStatement(statement.Body);
} }
writer.WriteLine("}"); writer.WriteLine("}");
@@ -573,7 +622,7 @@ static inline string *string_from_cstr(char *cstr)
if (@case.VariableName != null) if (@case.VariableName != null)
{ {
Debug.Assert(variantInfo.Type is not null); Debug.Assert(variantInfo.Type is not null);
writer.WriteLine($"{CType(variantInfo.Type, @case.VariableName.Ident)} = {target}.{@case.Variant.Ident};"); writer.WriteLine($"{TypeName(variantInfo.Type)} {@case.VariableName.Ident} = {target}.{@case.Variant.Ident};");
} }
EmitStatement(@case.Body); EmitStatement(@case.Body);
@@ -621,7 +670,7 @@ static inline string *string_from_cstr(char *cstr)
if (expression.Operation == TypedNodeExpressionBinary.Op.Add && expression.Left.Type is NubTypeString && expression.Right.Type is NubTypeString) if (expression.Operation == TypedNodeExpressionBinary.Op.Add && expression.Left.Type is NubTypeString && expression.Right.Type is NubTypeString)
{ {
scopes.Peek().DeconstructableNames.Add((name, expression.Type)); scopes.Peek().DeconstructableNames.Add((name, expression.Type));
writer.WriteLine($"{CType(NubTypeString.Instance, name)} = string_concat({left}, {right});"); writer.WriteLine($"{TypeName(NubTypeString.Instance)} {name} = string_concat({left}, {right});");
return name; return name;
} }
@@ -645,7 +694,7 @@ static inline string *string_from_cstr(char *cstr)
_ => throw new ArgumentOutOfRangeException() _ => throw new ArgumentOutOfRangeException()
}; };
writer.WriteLine($"{CType(expression.Type, name)} = {op};"); writer.WriteLine($"{TypeName(expression.Type)} {name} = {op};");
return name; return name;
} }
@@ -663,7 +712,7 @@ static inline string *string_from_cstr(char *cstr)
_ => throw new ArgumentOutOfRangeException() _ => throw new ArgumentOutOfRangeException()
}; };
writer.WriteLine($"{CType(expression.Type, name)} = {op};"); writer.WriteLine($"{TypeName(expression.Type)} {name} = {op};");
return name; return name;
} }
@@ -691,7 +740,7 @@ static inline string *string_from_cstr(char *cstr)
var initializerStrings = initializerValues.Select(x => $".{x.Key} = {x.Value}"); var initializerStrings = initializerValues.Select(x => $".{x.Key} = {x.Value}");
writer.WriteLine($"{CType(expression.Type, name)} = ({CType(expression.Type)}){{ {string.Join(", ", initializerStrings)} }};"); writer.WriteLine($"{TypeName(expression.Type)} {name} = ({TypeName(expression.Type)}){{ {string.Join(", ", initializerStrings)} }};");
return name; return name;
} }
@@ -716,12 +765,12 @@ static inline string *string_from_cstr(char *cstr)
EmitCopyConstructor(value, expression.Value.Type); EmitCopyConstructor(value, expression.Value.Type);
} }
writer.Write($"{CType(expression.Type, name)} = ({CType(expression.Type)}){{ .tag = {tag}"); writer.Write($"{TypeName(expression.Type)} {name} = ({TypeName(expression.Type)}){{ .tag = {tag}");
if (value != null) if (value != null)
writer.WriteLine($", .{enumVariantType.Variant} = {value} }};"); writer.WriteLine($", .{enumVariantType.Variant} = {value} }};");
else else
writer.WriteLine(" }};"); writer.WriteLine(" };");
return name; return name;
} }
@@ -729,13 +778,14 @@ static inline string *string_from_cstr(char *cstr)
private string EmitNodeExpressionArrayLiteral(TypedNodeExpressionArrayLiteral expression) private string EmitNodeExpressionArrayLiteral(TypedNodeExpressionArrayLiteral expression)
{ {
var name = Tmp(); var name = Tmp();
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
writer.WriteLine($"{CType(expression.Type, name)} = {{0}};"); writer.WriteLine($"{TypeName(expression.Type)} {name} = {TypeName(expression.Type)}_make();");
foreach (var value in expression.Values) foreach (var value in expression.Values)
{ {
var valueName = EmitExpression(value); var valueName = EmitExpression(value);
writer.WriteLine($"da_append(&{name}, {valueName});"); writer.WriteLine($"da_append({name}, {valueName});");
} }
return name; return name;
@@ -746,7 +796,7 @@ static inline string *string_from_cstr(char *cstr)
var name = Tmp(); var name = Tmp();
scopes.Peek().DeconstructableNames.Add((name, expression.Type)); scopes.Peek().DeconstructableNames.Add((name, expression.Type));
var value = EmitExpression(expression.Value); var value = EmitExpression(expression.Value);
writer.WriteLine($"{CType(expression.Type, name)} = string_from_cstr({value});"); writer.WriteLine($"{TypeName(expression.Type)} {name} = string_from_cstr({value});");
return name; return name;
} }
@@ -771,13 +821,13 @@ static inline string *string_from_cstr(char *cstr)
private string EmitExpressionArrayCount(TypedNodeExpressionArrayCount expression) private string EmitExpressionArrayCount(TypedNodeExpressionArrayCount expression)
{ {
var target = EmitExpression(expression.Target); var target = EmitExpression(expression.Target);
return $"{target}.count"; return $"{target}->count";
} }
private string EmitExpressionArrayPointer(TypedNodeExpressionArrayPointer expression) private string EmitExpressionArrayPointer(TypedNodeExpressionArrayPointer expression)
{ {
var target = EmitExpression(expression.Target); var target = EmitExpression(expression.Target);
return $"{target}.items"; return $"{target}->items";
} }
private string EmitNodeExpressionGlobalIdent(TypedNodeExpressionGlobalIdent expression) private string EmitNodeExpressionGlobalIdent(TypedNodeExpressionGlobalIdent expression)
@@ -794,43 +844,38 @@ static inline string *string_from_cstr(char *cstr)
var parameterValues = expression.Parameters.Select(EmitExpression).ToList(); var parameterValues = expression.Parameters.Select(EmitExpression).ToList();
var tmp = Tmp(); var tmp = Tmp();
writer.WriteLine($"{CType(expression.Type, tmp)} = {name}({string.Join(", ", parameterValues)});"); writer.WriteLine($"{TypeName(expression.Type)} {tmp} = {name}({string.Join(", ", parameterValues)});");
return tmp; return tmp;
} }
public string CType(NubType node, string? varName = null)
{
referencedTypes.Add(node);
return node switch
{
NubTypeVoid => "void" + (varName != null ? $" {varName}" : ""),
NubTypeBool => "bool" + (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 => $"i{type.Width}" + (varName != null ? $" {varName}" : ""),
NubTypeUInt type => $"u{type.Width}" + (varName != null ? $" {varName}" : ""),
NubTypePointer type => CType(type.To) + (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 readonly Dictionary<NubType, string> typeNames = []; private readonly Dictionary<NubType, string> typeNames = [];
private string CTypeNamed(NubType type, string? varName) private string TypeName(NubType type)
{ {
if (!typeNames.TryGetValue(type, out var name)) if (!typeNames.TryGetValue(type, out var name))
{ {
name = Tmp(); name = type switch
{
NubTypeVoid => "void",
NubTypeBool => "bool",
NubTypeStruct => Tmp(),
NubTypeAnonymousStruct => Tmp(),
NubTypeEnum => Tmp(),
NubTypeEnumVariant t => TypeName(t.EnumType),
NubTypeSInt t => $"int{t.Width}_t",
NubTypeUInt t => $"uint{t.Width}_t",
NubTypePointer => Tmp(),
NubTypeString => "string_ptr",
NubTypeChar => "char",
NubTypeFunc => Tmp(),
NubTypeArray => Tmp(),
_ => throw new NotImplementedException(),
};
typeNames[type] = name; typeNames[type] = name;
} }
return $"{name}{(varName != null ? $" {varName}" : "")}"; return name;
} }
private string Tmp() private string Tmp()
@@ -863,6 +908,11 @@ static inline string *string_from_cstr(char *cstr)
{ {
switch (type) switch (type)
{ {
case NubTypeArray arrayType:
{
writer.WriteLine($"{TypeName(type)}_rc_inc({value});");
break;
}
case NubTypeString: case NubTypeString:
{ {
writer.WriteLine($"string_rc_inc({value});"); writer.WriteLine($"string_rc_inc({value});");
@@ -934,6 +984,11 @@ static inline string *string_from_cstr(char *cstr)
{ {
switch (type) switch (type)
{ {
case NubTypeArray arrayType:
{
writer.WriteLine($"{TypeName(type)}_rc_dec({value});");
break;
}
case NubTypeString: case NubTypeString:
{ {
writer.WriteLine($"string_rc_dec({value});"); writer.WriteLine($"string_rc_dec({value});");
@@ -1078,4 +1133,4 @@ internal class IndentedTextWriter
disposed = true; disposed = true;
} }
} }
} }

View File

@@ -210,6 +210,7 @@ public class ModuleGraph
NodeTypeSInt type => NubTypeSInt.Get(type.Width), NodeTypeSInt type => NubTypeSInt.Get(type.Width),
NodeTypeUInt type => NubTypeUInt.Get(type.Width), NodeTypeUInt type => NubTypeUInt.Get(type.Width),
NodeTypeString => NubTypeString.Instance, NodeTypeString => NubTypeString.Instance,
NodeTypeChar => NubTypeChar.Instance,
NodeTypeVoid => NubTypeVoid.Instance, NodeTypeVoid => NubTypeVoid.Instance,
NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType, currentModule)), NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType, currentModule)),
_ => throw new ArgumentOutOfRangeException(nameof(node)) _ => throw new ArgumentOutOfRangeException(nameof(node))
@@ -442,4 +443,4 @@ public class Module(string name)
public NubType? Type { get; } = type; public NubType? Type { get; } = type;
} }
} }
} }

View File

@@ -102,6 +102,17 @@ public class NubTypeString : NubType
public override string ToString() => "string"; 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 public class NubTypeStruct : NubType
{ {
private static readonly Dictionary<(string Module, string Name), NubTypeStruct> Cache = new(); private static readonly Dictionary<(string Module, string Name), NubTypeStruct> Cache = new();
@@ -324,6 +335,10 @@ public class TypeEncoder
sb.Append('S'); sb.Append('S');
break; break;
case NubTypeChar:
sb.Append('C');
break;
case NubTypePointer p: case NubTypePointer p:
sb.Append("P("); sb.Append("P(");
EncodeType(sb, p.To); EncodeType(sb, p.To);
@@ -420,6 +435,7 @@ public class TypeDecoder
'U' => DecodeUInt(), 'U' => DecodeUInt(),
'I' => DecodeSInt(), 'I' => DecodeSInt(),
'S' => NubTypeString.Instance, 'S' => NubTypeString.Instance,
'C' => NubTypeChar.Instance,
'P' => DecodePointer(), 'P' => DecodePointer(),
'F' => DecodeFunc(), 'F' => DecodeFunc(),
'T' => DecodeStruct(), 'T' => DecodeStruct(),

View File

@@ -561,8 +561,12 @@ public class Parser
return new NodeTypeVoid(TokensFrom(startIndex)); return new NodeTypeVoid(TokensFrom(startIndex));
case "string": case "string":
return new NodeTypeString(TokensFrom(startIndex)); return new NodeTypeString(TokensFrom(startIndex));
case "char":
return new NodeTypeChar(TokensFrom(startIndex));
case "bool": case "bool":
return new NodeTypeBool(TokensFrom(startIndex)); return new NodeTypeBool(TokensFrom(startIndex));
case "int":
return new NodeTypeSInt(TokensFrom(startIndex), 64);
case "i8": case "i8":
return new NodeTypeSInt(TokensFrom(startIndex), 8); return new NodeTypeSInt(TokensFrom(startIndex), 8);
case "i16": case "i16":
@@ -571,6 +575,8 @@ public class Parser
return new NodeTypeSInt(TokensFrom(startIndex), 32); return new NodeTypeSInt(TokensFrom(startIndex), 32);
case "i64": case "i64":
return new NodeTypeSInt(TokensFrom(startIndex), 64); return new NodeTypeSInt(TokensFrom(startIndex), 64);
case "uint":
return new NodeTypeUInt(TokensFrom(startIndex), 64);
case "u8": case "u8":
return new NodeTypeUInt(TokensFrom(startIndex), 8); return new NodeTypeUInt(TokensFrom(startIndex), 8);
case "u16": case "u16":
@@ -1060,6 +1066,8 @@ public class NodeTypeBool(List<Token> tokens) : NodeType(tokens);
public class NodeTypeString(List<Token> tokens) : NodeType(tokens); public class NodeTypeString(List<Token> tokens) : NodeType(tokens);
public class NodeTypeChar(List<Token> tokens) : NodeType(tokens);
public class NodeTypeNamed(List<Token> tokens, List<TokenIdent> sections) : NodeType(tokens) public class NodeTypeNamed(List<Token> tokens, List<TokenIdent> sections) : NodeType(tokens)
{ {
public List<TokenIdent> Sections { get; } = sections; public List<TokenIdent> Sections { get; } = sections;
@@ -1090,4 +1098,4 @@ public class NodeTypeFunc(List<Token> tokens, List<NodeType> parameters, NodeTyp
{ {
public List<NodeType> Parameters { get; } = parameters; public List<NodeType> Parameters { get; } = parameters;
public NodeType ReturnType { get; } = returnType; public NodeType ReturnType { get; } = returnType;
} }

View File

@@ -147,18 +147,17 @@ if (!compileLib)
entryPoint = info.MangledName; entryPoint = info.MangledName;
} }
var output = Generator.Emit(functions, moduleGraph, entryPoint); var outFile = Generator.Emit(functions, moduleGraph, entryPoint);
File.WriteAllText(".build/out.c", output);
if (compileLib) if (compileLib)
{ {
Process.Start("gcc", ["-Og", "-g", "-fno-builtin", "-c", "-o", ".build/out.o", ".build/out.c", .. archivePaths]).WaitForExit(); 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(); Process.Start("ar", ["rcs", ".build/out.a", ".build/out.o"]).WaitForExit();
NubLib.Pack(".build/out.nublib", ".build/out.a", Manifest.Create(moduleGraph)); NubLib.Pack(".build/out.nublib", ".build/out.a", Manifest.Create(moduleGraph));
} }
else else
{ {
Process.Start("gcc", ["-Og", "-g", "-fno-builtin", "-o", ".build/out", ".build/out.c", .. archivePaths]).WaitForExit(); Process.Start("gcc", ["-Og", "-g", "-Wall", "-Werror", "-o", ".build/out", outFile, .. archivePaths]).WaitForExit();
} }
return 0; return 0;
@@ -177,4 +176,4 @@ static void CleanDirectory(string dirName)
CleanDirectory(subdir.FullName); CleanDirectory(subdir.FullName);
subdir.Delete(); subdir.Delete();
} }
} }

View File

@@ -494,7 +494,7 @@ public class TypeChecker
case "length": case "length":
return new TypedNodeExpressionStringLength(expression.Tokens, NubTypeUInt.Get(64), target); return new TypedNodeExpressionStringLength(expression.Tokens, NubTypeUInt.Get(64), target);
case "ptr": case "ptr":
return new TypedNodeExpressionStringPointer(expression.Tokens, NubTypePointer.Get(NubTypeUInt.Get(8)), target); return new TypedNodeExpressionStringPointer(expression.Tokens, NubTypePointer.Get(NubTypeChar.Instance), target);
default: default:
throw BasicError($"'{expression.Name.Ident}' is not a member of type {stringType}", expression.Name); throw BasicError($"'{expression.Name.Ident}' is not a member of type {stringType}", expression.Name);
} }
@@ -672,10 +672,10 @@ public class TypeChecker
throw BasicError($"Enum '{variantType.EnumType}' does not have a variant named '{variantType.Variant}'", expression.Type); throw BasicError($"Enum '{variantType.EnumType}' does not have a variant named '{variantType.Variant}'", expression.Type);
if (expression.Value == null && variant.Type is not null) if (expression.Value == null && variant.Type is not null)
throw BasicError($"Enum variant '{variantType.EnumType}' expects a value of type '{variant.Type}'", expression.Type); throw BasicError($"Enum variant '{variantType}' expects a value of type '{variant.Type}'", expression.Type);
if (expression.Value != null && variant.Type is null) if (expression.Value != null && variant.Type is null)
throw BasicError($"Enum variant '{variantType.EnumType}' does not expect any data", expression.Value); throw BasicError($"Enum variant '{variantType}' does not expect any data", expression.Value);
var value = expression.Value == null ? null : CheckExpression(expression.Value, variant.Type); var value = expression.Value == null ? null : CheckExpression(expression.Value, variant.Type);
@@ -684,7 +684,7 @@ public class TypeChecker
private TypedNodeExpressionStringConstructor CheckExpressionStringConstructor(NodeExpressionStringConstructor expression, NubType? expectedType) private TypedNodeExpressionStringConstructor CheckExpressionStringConstructor(NodeExpressionStringConstructor expression, NubType? expectedType)
{ {
var stringPoitnerType = NubTypePointer.Get(NubTypeUInt.Get(8)); var stringPoitnerType = NubTypePointer.Get(NubTypeChar.Instance);
var value = CheckExpression(expression.Value, stringPoitnerType); var value = CheckExpression(expression.Value, stringPoitnerType);
if (!value.Type.IsAssignableTo(stringPoitnerType)) if (!value.Type.IsAssignableTo(stringPoitnerType))
@@ -1103,4 +1103,4 @@ public class TypedNodeExpressionUnary(List<Token> tokens, NubType type, TypedNod
Negate, Negate,
Invert, Invert,
} }
} }

21
examples/build Executable file
View 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

View File

@@ -1,15 +0,0 @@
set -e
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

View File

@@ -1,5 +1,5 @@
module sys module sys
export extern func read(fd: u32, buf: ^u8, count: u64): i64 export extern func read(fd: u32, buf: ^char, count: u64): i64
export extern func write(fd: u32, buf: ^u8, count: u64): i64 export extern func write(fd: u32, buf: ^char, count: u64): i64
export extern func open(fileName: ^u8, flags: i32, mode: u16): i64 export extern func open(fileName: ^char, flags: i32, mode: u16): i64

View File

@@ -11,11 +11,22 @@ enum Message {
} }
func main(): i32 { func main(): i32 {
let names = ["a", "b", "c", "d"]
for name in names { let x = new string("test".ptr) + " " + "uwu"
core::println(name) 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 return 0
} }