Compare commits
26 Commits
270be1f740
...
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 |
@@ -17,26 +17,138 @@ public class Generator
|
||||
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 ModuleGraph moduleGraph;
|
||||
private readonly string? entryPoint;
|
||||
private IndentedTextWriter writer = new();
|
||||
private HashSet<NubType> referencedTypes = new();
|
||||
private readonly HashSet<NubType> emittedTypes = new();
|
||||
private readonly Dictionary<string, string> referencedStringLiterals = [];
|
||||
private readonly HashSet<NubType> emittedTypes = [];
|
||||
private readonly Stack<Scope> scopes = new();
|
||||
private int tmpNameIndex = 0;
|
||||
|
||||
private string Emit()
|
||||
{
|
||||
var outPath = ".build";
|
||||
var fileName = "out.c";
|
||||
|
||||
if (entryPoint != null)
|
||||
{
|
||||
writer.WriteLine($$"""
|
||||
int main(int argc, char *argv[])
|
||||
writer.WriteLine("int main(int argc, char *argv[])");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
return {{entryPoint}}();
|
||||
writer.WriteLine($"return {entryPoint}();");
|
||||
}
|
||||
""");
|
||||
|
||||
writer.WriteLine("}");
|
||||
writer.WriteLine();
|
||||
}
|
||||
|
||||
@@ -45,14 +157,12 @@ public class Generator
|
||||
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");
|
||||
|
||||
if (info.Source == Module.DefinitionSource.Imported || info.Extern)
|
||||
writer.Write("extern ");
|
||||
else if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported)
|
||||
if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported)
|
||||
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("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
@@ -64,7 +174,7 @@ public class Generator
|
||||
writer.WriteLine();
|
||||
}
|
||||
|
||||
var implementations = writer.ToString();
|
||||
var definitions = writer.ToString();
|
||||
|
||||
writer = new IndentedTextWriter();
|
||||
|
||||
@@ -80,37 +190,63 @@ public class Generator
|
||||
writer.Write("static ");
|
||||
|
||||
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
|
||||
writer.WriteLine($"{CType(info.Type, info.MangledName)};");
|
||||
writer.WriteLine($"{TypeName(info.Type)} {info.MangledName};");
|
||||
|
||||
writer.WriteLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (name, value) in referencedStringLiterals)
|
||||
{
|
||||
writer.WriteLine
|
||||
(
|
||||
$$"""
|
||||
static string {{name}} = (string){
|
||||
.data = "{{value}}",
|
||||
.length = {{Encoding.UTF8.GetByteCount(value)}},
|
||||
.ref = 0,
|
||||
.flags = FLAG_STRING_LITERAL
|
||||
};
|
||||
|
||||
"""
|
||||
);
|
||||
}
|
||||
|
||||
var declarations = writer.ToString();
|
||||
|
||||
writer = new IndentedTextWriter();
|
||||
|
||||
writer.WriteLine("""
|
||||
#include <float.h>
|
||||
#include <stdarg.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
""");
|
||||
|
||||
while (referencedTypes.Count != 0)
|
||||
while (emittedTypes.Count != typeNames.Count)
|
||||
{
|
||||
var nextTypes = typeNames.Keys.ToArray();
|
||||
foreach (var type in nextTypes)
|
||||
{
|
||||
var type = referencedTypes.ElementAt(0);
|
||||
EmitTypeDefinitionIfNotEmitted(type);
|
||||
referencedTypes.Remove(type);
|
||||
}
|
||||
}
|
||||
|
||||
var header = writer.ToString();
|
||||
var types = writer.ToString();
|
||||
|
||||
return $"{header}\n{declarations}\n{implementations}";
|
||||
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)
|
||||
@@ -120,60 +256,10 @@ public class Generator
|
||||
|
||||
emittedTypes.Add(type);
|
||||
|
||||
var name = TypeName(type);
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case NubTypeString stringType:
|
||||
{
|
||||
writer.WriteLine($"struct {NameMangler.Mangle("core", "string", stringType)}");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
writer.WriteLine("char *data;");
|
||||
writer.WriteLine("size_t length;");
|
||||
writer.WriteLine("int32_t ref;");
|
||||
writer.WriteLine("uint32_t flags;");
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine();
|
||||
|
||||
writer.WriteLine("#define FLAG_STRING_LITERAL 1");
|
||||
writer.WriteLine();
|
||||
|
||||
writer.WriteLine($"static inline void rc_inc({CType(NubTypeString.Instance, "string")})");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
writer.WriteLine($"string->ref += 1;");
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
writer.WriteLine();
|
||||
|
||||
writer.WriteLine($"static inline void rc_dec({CType(NubTypeString.Instance, "string")})");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
writer.WriteLine($"string->ref -= 1;");
|
||||
writer.WriteLine($"if (string->ref <= 0)");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
writer.WriteLine($"if ((string->flags & FLAG_STRING_LITERAL) == 0)");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
writer.WriteLine($"free(string->data);");
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
writer.WriteLine($"free(string);");
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
}
|
||||
case NubTypeStruct structType:
|
||||
{
|
||||
if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo)
|
||||
@@ -182,21 +268,19 @@ 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())
|
||||
{
|
||||
foreach (var field in structInfo.Fields)
|
||||
{
|
||||
writer.WriteLine($"{CType(field.Type, field.Name)};");
|
||||
writer.WriteLine($"{TypeName(field.Type)} {field.Name};");
|
||||
}
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine($"}} {name};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
@@ -206,16 +290,16 @@ 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())
|
||||
{
|
||||
foreach (var field in anonymousStructType.Fields)
|
||||
{
|
||||
writer.WriteLine($"{CType(field.Type, field.Name)};");
|
||||
writer.WriteLine($"{TypeName(field.Type)} {field.Name};");
|
||||
}
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine($"}} {name};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
@@ -226,9 +310,14 @@ public class Generator
|
||||
throw new UnreachableException();
|
||||
|
||||
foreach (var variant in enumInfo.Variants)
|
||||
{
|
||||
if (variant.Type is not null)
|
||||
{
|
||||
EmitTypeDefinitionIfNotEmitted(variant.Type);
|
||||
}
|
||||
}
|
||||
|
||||
writer.WriteLine($"struct {NameMangler.Mangle(enumType.Module, enumType.Name, enumType)}");
|
||||
writer.WriteLine("typedef struct");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
{
|
||||
@@ -239,12 +328,15 @@ public class Generator
|
||||
{
|
||||
foreach (var variant in enumInfo.Variants)
|
||||
{
|
||||
writer.WriteLine($"{CType(variant.Type, variant.Name)};");
|
||||
if (variant.Type is not null)
|
||||
{
|
||||
writer.WriteLine($"{TypeName(variant.Type)} {variant.Name};");
|
||||
}
|
||||
}
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
}
|
||||
writer.WriteLine("};");
|
||||
writer.WriteLine($"}} {name};");
|
||||
writer.WriteLine();
|
||||
|
||||
break;
|
||||
@@ -252,6 +344,98 @@ public class Generator
|
||||
case NubTypeEnumVariant variantType:
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -285,6 +469,9 @@ public class Generator
|
||||
case TypedNodeStatementWhile statement:
|
||||
EmitStatementWhile(statement);
|
||||
break;
|
||||
case TypedNodeStatementFor statement:
|
||||
EmitStatementFor(statement);
|
||||
break;
|
||||
case TypedNodeStatementMatch statement:
|
||||
EmitStatementMatch(statement);
|
||||
break;
|
||||
@@ -318,10 +505,8 @@ public class Generator
|
||||
if (statement.Value != null)
|
||||
{
|
||||
var value = EmitExpression(statement.Value);
|
||||
var variableName = TmpName();
|
||||
writer.WriteLine($"{CType(statement.Value.Type, variableName)} = {value};");
|
||||
EmitCleanupAllScopes();
|
||||
writer.WriteLine($"return {variableName};");
|
||||
writer.WriteLine($"return {value};");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -336,7 +521,7 @@ public class Generator
|
||||
{
|
||||
var value = EmitExpression(statement.Value);
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -395,6 +580,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($"{TypeName(arrayType.ElementType)} {statement.VariableName.Ident} = {array}->items[{index}];");
|
||||
EmitStatement(statement.Body);
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private void EmitStatementMatch(TypedNodeStatementMatch statement)
|
||||
{
|
||||
var target = EmitExpression(statement.Target);
|
||||
@@ -419,7 +619,12 @@ public class Generator
|
||||
using (writer.Indent())
|
||||
{
|
||||
PushScope();
|
||||
writer.WriteLine($"{CType(variantInfo.Type, @case.VariableName.Ident)} = {target}.{@case.Variant.Ident};");
|
||||
if (@case.VariableName != null)
|
||||
{
|
||||
Debug.Assert(variantInfo.Type is not null);
|
||||
writer.WriteLine($"{TypeName(variantInfo.Type)} {@case.VariableName.Ident} = {target}.{@case.Variant.Ident};");
|
||||
}
|
||||
|
||||
EmitStatement(@case.Body);
|
||||
PopScope();
|
||||
writer.WriteLine("break;");
|
||||
@@ -432,7 +637,7 @@ public class Generator
|
||||
|
||||
private string EmitExpression(TypedNodeExpression node)
|
||||
{
|
||||
var value = node switch
|
||||
return node switch
|
||||
{
|
||||
TypedNodeExpressionBinary expression => EmitExpressionBinary(expression),
|
||||
TypedNodeExpressionUnary expression => EmitExpressionUnary(expression),
|
||||
@@ -441,18 +646,18 @@ 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),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node), node, null)
|
||||
};
|
||||
|
||||
var tmp = TmpName();
|
||||
writer.WriteLine($"{CType(node.Type, tmp)} = {value};");
|
||||
return tmp;
|
||||
}
|
||||
|
||||
private string EmitExpressionBinary(TypedNodeExpressionBinary expression)
|
||||
@@ -460,7 +665,16 @@ public class Generator
|
||||
var left = EmitExpression(expression.Left);
|
||||
var right = EmitExpression(expression.Right);
|
||||
|
||||
return expression.Operation switch
|
||||
var name = Tmp();
|
||||
|
||||
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($"{TypeName(NubTypeString.Instance)} {name} = string_concat({left}, {right});");
|
||||
return name;
|
||||
}
|
||||
|
||||
var op = expression.Operation switch
|
||||
{
|
||||
TypedNodeExpressionBinary.Op.Add => $"({left} + {right})",
|
||||
TypedNodeExpressionBinary.Op.Subtract => $"({left} - {right})",
|
||||
@@ -479,39 +693,40 @@ public class Generator
|
||||
TypedNodeExpressionBinary.Op.LogicalOr => $"({left} || {right})",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
|
||||
writer.WriteLine($"{TypeName(expression.Type)} {name} = {op};");
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private string EmitExpressionUnary(TypedNodeExpressionUnary expression)
|
||||
{
|
||||
var target = EmitExpression(expression.Target);
|
||||
|
||||
return expression.Operation switch
|
||||
var name = Tmp();
|
||||
|
||||
var op = expression.Operation switch
|
||||
{
|
||||
TypedNodeExpressionUnary.Op.Negate => $"(-{target})",
|
||||
TypedNodeExpressionUnary.Op.Invert => $"(!{target})",
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
};
|
||||
}
|
||||
|
||||
private string EmitExpressionStringLiteral(TypedNodeExpressionStringLiteral expression)
|
||||
{
|
||||
var name = TmpName();
|
||||
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
|
||||
|
||||
var variable = CType(expression.Type, name);
|
||||
|
||||
writer.WriteLine($"{variable} = malloc(sizeof(struct {NameMangler.Mangle("core", "string", expression.Type)}));");
|
||||
writer.WriteLine($"{name}->data = \"{expression.Value.Value}\";");
|
||||
writer.WriteLine($"{name}->length = {expression.Value.Value.Length};");
|
||||
writer.WriteLine($"{name}->ref = 1;");
|
||||
writer.WriteLine($"{name}->flags = FLAG_STRING_LITERAL;");
|
||||
writer.WriteLine($"{TypeName(expression.Type)} {name} = {op};");
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private string EmitExpressionStringLiteral(TypedNodeExpressionStringLiteral expression)
|
||||
{
|
||||
var name = Tmp();
|
||||
referencedStringLiterals.Add(name, expression.Value.Value);
|
||||
return $"(&{name})";
|
||||
}
|
||||
|
||||
private string EmitExpressionStructLiteral(TypedNodeExpressionStructLiteral expression)
|
||||
{
|
||||
var name = TmpName();
|
||||
var name = Tmp();
|
||||
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
|
||||
|
||||
var initializerValues = new Dictionary<string, string>();
|
||||
@@ -525,14 +740,14 @@ public class Generator
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private string EmitExpressionEnumLiteral(TypedNodeExpressionEnumLiteral expression)
|
||||
{
|
||||
var name = TmpName();
|
||||
var name = Tmp();
|
||||
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
|
||||
|
||||
var enumVariantType = (NubTypeEnumVariant)expression.Type;
|
||||
@@ -543,11 +758,45 @@ public class Generator
|
||||
var enumInfo = (Module.TypeInfoEnum)info;
|
||||
var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == enumVariantType.Variant);
|
||||
|
||||
var value = EmitExpression(expression.Value);
|
||||
string? value = null;
|
||||
if (expression.Value != null)
|
||||
{
|
||||
value = EmitExpression(expression.Value);
|
||||
EmitCopyConstructor(value, expression.Value.Type);
|
||||
}
|
||||
|
||||
writer.WriteLine($"{CType(expression.Type, name)} = ({CType(expression.Type)}){{ .tag = {tag}, .{enumVariantType.Variant} = {value} }};");
|
||||
writer.Write($"{TypeName(expression.Type)} {name} = ({TypeName(expression.Type)}){{ .tag = {tag}");
|
||||
|
||||
if (value != null)
|
||||
writer.WriteLine($", .{enumVariantType.Variant} = {value} }};");
|
||||
else
|
||||
writer.WriteLine(" };");
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private string EmitNodeExpressionArrayLiteral(TypedNodeExpressionArrayLiteral expression)
|
||||
{
|
||||
var name = Tmp();
|
||||
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
|
||||
|
||||
writer.WriteLine($"{TypeName(expression.Type)} {name} = {TypeName(expression.Type)}_make();");
|
||||
|
||||
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($"{TypeName(expression.Type)} {name} = string_from_cstr({value});");
|
||||
return name;
|
||||
}
|
||||
|
||||
@@ -569,6 +818,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))
|
||||
@@ -581,36 +842,43 @@ public class Generator
|
||||
{
|
||||
var name = EmitExpression(expression.Target);
|
||||
var parameterValues = expression.Parameters.Select(EmitExpression).ToList();
|
||||
return $"{name}({string.Join(", ", parameterValues)})";
|
||||
|
||||
var tmp = Tmp();
|
||||
writer.WriteLine($"{TypeName(expression.Type)} {tmp} = {name}({string.Join(", ", parameterValues)});");
|
||||
return tmp;
|
||||
}
|
||||
|
||||
public string CType(NubType node, string? varName = null)
|
||||
{
|
||||
referencedTypes.Add(node);
|
||||
private readonly Dictionary<NubType, string> typeNames = [];
|
||||
|
||||
return node switch
|
||||
private string TypeName(NubType type)
|
||||
{
|
||||
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}" : ""),
|
||||
NubTypeEnumVariant type => CType(type.EnumType, varName),
|
||||
NubTypeSInt type => $"int{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypeUInt type => $"uint{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
||||
NubTypePointer type => CType(type.To) + (varName != null ? $" *{varName}" : "*"),
|
||||
NubTypeString type => $"struct {NameMangler.Mangle("core", "string", type)}" + (varName != null ? $" *{varName}" : "*"),
|
||||
NubTypeFunc type => $"{CType(type.ReturnType)} (*{varName})({string.Join(", ", type.Parameters.Select(p => CType(p)))})",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node), node, null)
|
||||
if (!typeNames.TryGetValue(type, out var name))
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
private static string CTypeAnonymousStruct(NubTypeAnonymousStruct type, string? varName)
|
||||
{
|
||||
return $"struct {NameMangler.Mangle("anonymous", "struct", type)}{(varName != null ? $" {varName}" : "")}";
|
||||
return name;
|
||||
}
|
||||
|
||||
private string TmpName()
|
||||
private string Tmp()
|
||||
{
|
||||
return $"_tmp{tmpNameIndex++}";
|
||||
}
|
||||
@@ -640,9 +908,14 @@ public class Generator
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case NubTypeArray arrayType:
|
||||
{
|
||||
writer.WriteLine($"{TypeName(type)}_rc_inc({value});");
|
||||
break;
|
||||
}
|
||||
case NubTypeString:
|
||||
{
|
||||
writer.WriteLine($"rc_inc({value});");
|
||||
writer.WriteLine($"string_rc_inc({value});");
|
||||
break;
|
||||
}
|
||||
case NubTypeStruct structType:
|
||||
@@ -677,6 +950,8 @@ public class Generator
|
||||
{
|
||||
Module.TypeInfoEnum.Variant variant = enumInfo.Variants[i];
|
||||
|
||||
if (variant.Type is not null)
|
||||
{
|
||||
writer.WriteLine($"case {i}:");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
@@ -687,6 +962,7 @@ public class Generator
|
||||
writer.WriteLine("}");
|
||||
}
|
||||
}
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
break;
|
||||
}
|
||||
@@ -696,8 +972,9 @@ public class Generator
|
||||
throw new UnreachableException();
|
||||
|
||||
var variant = enumInfo.Variants.First(x => x.Name == enumVariantType.Variant);
|
||||
|
||||
if (variant.Type is not null)
|
||||
EmitCopyConstructor($"{value}.{variant.Name}", variant.Type);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -707,9 +984,14 @@ public class Generator
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case NubTypeArray arrayType:
|
||||
{
|
||||
writer.WriteLine($"{TypeName(type)}_rc_dec({value});");
|
||||
break;
|
||||
}
|
||||
case NubTypeString:
|
||||
{
|
||||
writer.WriteLine($"rc_dec({value});");
|
||||
writer.WriteLine($"string_rc_dec({value});");
|
||||
break;
|
||||
}
|
||||
case NubTypeStruct structType:
|
||||
@@ -743,7 +1025,8 @@ public class Generator
|
||||
for (int i = 0; i < enumInfo.Variants.Count; i++)
|
||||
{
|
||||
var variant = enumInfo.Variants[i];
|
||||
|
||||
if (variant.Type is not null)
|
||||
{
|
||||
writer.WriteLine($"case {i}:");
|
||||
writer.WriteLine("{");
|
||||
using (writer.Indent())
|
||||
@@ -754,6 +1037,7 @@ public class Generator
|
||||
writer.WriteLine("}");
|
||||
}
|
||||
}
|
||||
}
|
||||
writer.WriteLine("}");
|
||||
break;
|
||||
}
|
||||
@@ -763,8 +1047,9 @@ public class Generator
|
||||
throw new UnreachableException();
|
||||
|
||||
var variant = enumInfo.Variants.First(x => x.Name == enumVariantType.Variant);
|
||||
|
||||
if (variant.Type is not null)
|
||||
EmitCopyDestructor($"{value}.{variant.Name}", variant.Type);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ public class ModuleGraph
|
||||
|
||||
if (typeInfo is Module.TypeInfoEnum enumType)
|
||||
{
|
||||
var variants = enumDef.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name.Ident, ResolveType(v.Type, module.Name))).ToList();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,9 @@ public class ModuleGraph
|
||||
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))
|
||||
};
|
||||
}
|
||||
@@ -435,10 +437,10 @@ public class Module(string name)
|
||||
this.variants = variants;
|
||||
}
|
||||
|
||||
public class Variant(string name, NubType type)
|
||||
public class Variant(string name, NubType? type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType Type { get; } = type;
|
||||
public NubType? Type { get; } = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,7 +104,7 @@ public record Manifest(Dictionary<string, Manifest.Module> Modules)
|
||||
|
||||
public record TypeInfoEnum(bool Exported, IReadOnlyList<TypeInfoEnum.Variant> Variants) : TypeInfo(Exported)
|
||||
{
|
||||
public record Variant(string Name, NubType Type);
|
||||
public record Variant(string Name, NubType? Type);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,17 @@ public class NubTypeString : NubType
|
||||
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();
|
||||
@@ -256,6 +267,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)
|
||||
@@ -302,6 +335,10 @@ public class TypeEncoder
|
||||
sb.Append('S');
|
||||
break;
|
||||
|
||||
case NubTypeChar:
|
||||
sb.Append('C');
|
||||
break;
|
||||
|
||||
case NubTypePointer p:
|
||||
sb.Append("P(");
|
||||
EncodeType(sb, p.To);
|
||||
@@ -355,6 +392,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);
|
||||
}
|
||||
@@ -392,10 +435,12 @@ public class TypeDecoder
|
||||
'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")
|
||||
};
|
||||
}
|
||||
@@ -531,6 +576,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)
|
||||
|
||||
@@ -86,17 +86,7 @@ public class Parser
|
||||
throw BasicError("Invalid modifier for function", modifier.Value);
|
||||
|
||||
var name = ExpectIdent();
|
||||
var parameters = new List<NodeDefinitionFunc.Param>();
|
||||
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
while (!TryExpectSymbol(Symbol.CloseParen))
|
||||
{
|
||||
var paramStartIndex = index;
|
||||
var parameterName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var parameterType = ParseType();
|
||||
parameters.Add(new NodeDefinitionFunc.Param(TokensFrom(paramStartIndex), parameterName, parameterType));
|
||||
}
|
||||
var parameters = ParseFuncParameters();
|
||||
|
||||
NodeType? returnType = null;
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
@@ -132,6 +122,7 @@ public class Parser
|
||||
var fieldName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var fieldType = ParseType();
|
||||
TryExpectSymbol(Symbol.Comma);
|
||||
fields.Add(new NodeDefinitionStruct.Field(TokensFrom(fieldStartIndex), fieldName, fieldType));
|
||||
}
|
||||
|
||||
@@ -154,8 +145,13 @@ public class Parser
|
||||
{
|
||||
var variantsStartIndex = index;
|
||||
var variantName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var variantType = ParseType();
|
||||
|
||||
NodeType? variantType = null;
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
variantType = ParseType();
|
||||
|
||||
TryExpectSymbol(Symbol.Comma);
|
||||
|
||||
variants.Add(new NodeDefinitionEnum.Variant(TokensFrom(variantsStartIndex), variantName, variantType));
|
||||
}
|
||||
|
||||
@@ -180,6 +176,35 @@ public class Parser
|
||||
throw BasicError("Not a valid definition", Peek());
|
||||
}
|
||||
|
||||
private List<NodeDefinitionFunc.Param> ParseFuncParameters()
|
||||
{
|
||||
var parameters = new List<NodeDefinitionFunc.Param>();
|
||||
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (TryExpectSymbol(Symbol.CloseParen))
|
||||
break;
|
||||
|
||||
var startIndex = index;
|
||||
|
||||
var name = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var type = ParseType();
|
||||
|
||||
parameters.Add(new NodeDefinitionFunc.Param(TokensFrom(startIndex), name, type));
|
||||
|
||||
if (!TryExpectSymbol(Symbol.Comma))
|
||||
{
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private NodeStatement ParseStatement()
|
||||
{
|
||||
var startIndex = index;
|
||||
@@ -238,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))
|
||||
@@ -251,10 +285,10 @@ public class Parser
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var caseStartIndex = index;
|
||||
var type = ExpectIdent();
|
||||
var variableName = ExpectIdent();
|
||||
var variant = ExpectIdent();
|
||||
TryExpectIdent(out var variableName);
|
||||
var body = ParseStatement();
|
||||
cases.Add(new NodeStatementMatch.Case(TokensFrom(caseStartIndex), type, variableName, body));
|
||||
cases.Add(new NodeStatementMatch.Case(TokensFrom(caseStartIndex), variant, variableName, body));
|
||||
}
|
||||
|
||||
return new NodeStatementMatch(TokensFrom(startIndex), target, cases);
|
||||
@@ -338,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>();
|
||||
@@ -380,13 +427,30 @@ public class Parser
|
||||
|
||||
expr = new NodeExpressionIdent(TokensFrom(startIndex), sections);
|
||||
}
|
||||
else if (TryExpectKeyword(Keyword.Struct))
|
||||
else if (TryExpectKeyword(Keyword.New))
|
||||
{
|
||||
var type = ParseType();
|
||||
|
||||
var initializers = new List<NodeExpressionStructLiteral.Initializer>();
|
||||
if (type is NodeTypeString)
|
||||
{
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
var value = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
|
||||
ExpectSymbol(Symbol.OpenCurly);
|
||||
expr = new NodeExpressionStringConstructor(TokensFrom(startIndex), value);
|
||||
}
|
||||
else if (type is NodeTypeNamed namedType)
|
||||
{
|
||||
if (TryExpectSymbol(Symbol.OpenParen))
|
||||
{
|
||||
var value = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
|
||||
expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), namedType, value);
|
||||
}
|
||||
else if (TryExpectSymbol(Symbol.OpenCurly))
|
||||
{
|
||||
var initializers = new List<NodeExpressionStructLiteral.Initializer>();
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var initializerStartIndex = startIndex;
|
||||
@@ -396,14 +460,17 @@ public class Parser
|
||||
initializers.Add(new NodeExpressionStructLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue));
|
||||
}
|
||||
|
||||
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), type, initializers);
|
||||
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), null, initializers);
|
||||
}
|
||||
else if (TryExpectKeyword(Keyword.Enum))
|
||||
else
|
||||
{
|
||||
var type = ParseType();
|
||||
var value = ParseExpression();
|
||||
|
||||
expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), type, value);
|
||||
expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), namedType, null);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw BasicError($"Expected named type or string", type);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -422,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);
|
||||
}
|
||||
@@ -476,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)
|
||||
@@ -484,8 +561,12 @@ public class Parser
|
||||
return new NodeTypeVoid(TokensFrom(startIndex));
|
||||
case "string":
|
||||
return new NodeTypeString(TokensFrom(startIndex));
|
||||
case "char":
|
||||
return new NodeTypeChar(TokensFrom(startIndex));
|
||||
case "bool":
|
||||
return new NodeTypeBool(TokensFrom(startIndex));
|
||||
case "int":
|
||||
return new NodeTypeSInt(TokensFrom(startIndex), 64);
|
||||
case "i8":
|
||||
return new NodeTypeSInt(TokensFrom(startIndex), 8);
|
||||
case "i16":
|
||||
@@ -494,6 +575,8 @@ public class Parser
|
||||
return new NodeTypeSInt(TokensFrom(startIndex), 32);
|
||||
case "i64":
|
||||
return new NodeTypeSInt(TokensFrom(startIndex), 64);
|
||||
case "uint":
|
||||
return new NodeTypeUInt(TokensFrom(startIndex), 64);
|
||||
case "u8":
|
||||
return new NodeTypeUInt(TokensFrom(startIndex), 8);
|
||||
case "u16":
|
||||
@@ -710,6 +793,11 @@ public class Parser
|
||||
{
|
||||
return new CompileException(Diagnostic.Error(message).At(fileName, ident).Build());
|
||||
}
|
||||
|
||||
private CompileException BasicError(string message, Node? node)
|
||||
{
|
||||
return new CompileException(Diagnostic.Error(message).At(fileName, node).Build());
|
||||
}
|
||||
}
|
||||
|
||||
public class Ast(string fileName, TokenIdent moduleName, List<NodeDefinition> definitions)
|
||||
@@ -769,10 +857,10 @@ public class NodeDefinitionEnum(List<Token> tokens, bool exported, TokenIdent na
|
||||
public TokenIdent Name { get; } = name;
|
||||
public List<Variant> Variants { get; } = variants;
|
||||
|
||||
public class Variant(List<Token> tokens, TokenIdent name, NodeType type) : Node(tokens)
|
||||
public class Variant(List<Token> tokens, TokenIdent name, NodeType? type) : Node(tokens)
|
||||
{
|
||||
public TokenIdent Name { get; } = name;
|
||||
public NodeType Type { get; } = type;
|
||||
public NodeType? Type { get; } = type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -833,15 +921,22 @@ 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;
|
||||
public List<Case> Cases { get; } = cases;
|
||||
|
||||
public class Case(List<Token> tokens, TokenIdent type, TokenIdent variableName, NodeStatement body) : Node(tokens)
|
||||
public class Case(List<Token> tokens, TokenIdent type, TokenIdent? variableName, NodeStatement body) : Node(tokens)
|
||||
{
|
||||
public TokenIdent Variant { get; } = type;
|
||||
public TokenIdent VariableName { get; } = variableName;
|
||||
public TokenIdent? VariableName { get; } = variableName;
|
||||
public NodeStatement Body { get; } = body;
|
||||
}
|
||||
}
|
||||
@@ -863,9 +958,9 @@ public class NodeExpressionBoolLiteral(List<Token> tokens, TokenBoolLiteral valu
|
||||
public TokenBoolLiteral Value { get; } = value;
|
||||
}
|
||||
|
||||
public class NodeExpressionStructLiteral(List<Token> tokens, NodeType? type, List<NodeExpressionStructLiteral.Initializer> initializers) : NodeExpression(tokens)
|
||||
public class NodeExpressionStructLiteral(List<Token> tokens, NodeTypeNamed? type, List<NodeExpressionStructLiteral.Initializer> initializers) : NodeExpression(tokens)
|
||||
{
|
||||
public NodeType? Type { get; } = type;
|
||||
public NodeTypeNamed? Type { get; } = type;
|
||||
public List<Initializer> Initializers { get; } = initializers;
|
||||
|
||||
public class Initializer(List<Token> tokens, TokenIdent name, NodeExpression value) : Node(tokens)
|
||||
@@ -875,9 +970,19 @@ public class NodeExpressionStructLiteral(List<Token> tokens, NodeType? type, Lis
|
||||
}
|
||||
}
|
||||
|
||||
public class NodeExpressionEnumLiteral(List<Token> tokens, NodeType type, NodeExpression value) : NodeExpression(tokens)
|
||||
public class NodeExpressionEnumLiteral(List<Token> tokens, NodeTypeNamed type, NodeExpression? value) : NodeExpression(tokens)
|
||||
{
|
||||
public NodeTypeNamed Type { get; } = type;
|
||||
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 NodeType Type { get; } = type;
|
||||
public NodeExpression Value { get; } = value;
|
||||
}
|
||||
|
||||
@@ -961,6 +1066,8 @@ public class NodeTypeBool(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 List<TokenIdent> Sections { get; } = sections;
|
||||
@@ -977,6 +1084,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,27 +144,20 @@ 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;
|
||||
}
|
||||
|
||||
var output = Generator.Emit(functions, moduleGraph, entryPoint);
|
||||
File.WriteAllText(".build/out.c", output);
|
||||
var outFile = Generator.Emit(functions, moduleGraph, entryPoint);
|
||||
|
||||
if (compileLib)
|
||||
{
|
||||
Process.Start("gcc", ["-Og", "-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();
|
||||
NubLib.Pack(".build/out.nublib", ".build/out.a", Manifest.Create(moduleGraph));
|
||||
}
|
||||
else
|
||||
{
|
||||
Process.Start("gcc", ["-Og", "-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;
|
||||
|
||||
@@ -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();
|
||||
@@ -389,11 +399,14 @@ public class Tokenizer
|
||||
"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),
|
||||
@@ -496,6 +509,8 @@ public enum Symbol
|
||||
CloseCurly,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
OpenSquare,
|
||||
CloseSquare,
|
||||
Comma,
|
||||
Period,
|
||||
Colon,
|
||||
@@ -538,11 +553,14 @@ public enum Keyword
|
||||
Struct,
|
||||
Packed,
|
||||
Enum,
|
||||
New,
|
||||
Match,
|
||||
Let,
|
||||
If,
|
||||
Else,
|
||||
While,
|
||||
For,
|
||||
In,
|
||||
Return,
|
||||
Module,
|
||||
Export,
|
||||
@@ -564,6 +582,8 @@ public static class TokenExtensions
|
||||
Symbol.CloseCurly => "}",
|
||||
Symbol.OpenParen => "(",
|
||||
Symbol.CloseParen => ")",
|
||||
Symbol.OpenSquare => "[",
|
||||
Symbol.CloseSquare => "]",
|
||||
Symbol.Comma => ",",
|
||||
Symbol.Period => ".",
|
||||
Symbol.Colon => ":",
|
||||
@@ -605,11 +625,14 @@ public static class TokenExtensions
|
||||
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",
|
||||
|
||||
@@ -24,7 +24,7 @@ public class TypeChecker
|
||||
private readonly NodeDefinitionFunc function;
|
||||
private NubType functionReturnType = null!;
|
||||
private readonly ModuleGraph moduleGraph;
|
||||
private readonly Scope scope = new();
|
||||
private readonly Stack<Dictionary<string, NubType>> scopes = new();
|
||||
|
||||
private TypedNodeDefinitionFunc? CheckFunction(out List<Diagnostic> diagnostics)
|
||||
{
|
||||
@@ -51,7 +51,7 @@ public class TypeChecker
|
||||
}
|
||||
}
|
||||
|
||||
using (scope.EnterScope())
|
||||
using (EnterScope())
|
||||
{
|
||||
foreach (var parameter in function.Parameters)
|
||||
{
|
||||
@@ -60,6 +60,7 @@ public class TypeChecker
|
||||
try
|
||||
{
|
||||
parameterType = ResolveType(parameter.Type);
|
||||
DeclareLocalIdentifier(parameter.Name, parameterType);
|
||||
}
|
||||
catch (CompileException e)
|
||||
{
|
||||
@@ -68,7 +69,6 @@ public class TypeChecker
|
||||
continue;
|
||||
}
|
||||
|
||||
scope.DeclareIdentifier(parameter.Name.Ident, parameterType);
|
||||
parameters.Add(new TypedNodeDefinitionFunc.Param(parameter.Tokens, parameter.Name, parameterType));
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
};
|
||||
@@ -114,7 +115,7 @@ public class TypeChecker
|
||||
|
||||
private TypedNodeStatementBlock CheckStatementBlock(NodeStatementBlock statement)
|
||||
{
|
||||
using (scope.EnterScope())
|
||||
using (EnterScope())
|
||||
{
|
||||
var statements = statement.Statements.Select(CheckStatement).ToList();
|
||||
return new TypedNodeStatementBlock(statement.Tokens, statements);
|
||||
@@ -137,8 +138,19 @@ public class TypeChecker
|
||||
if (!condition.Type.IsAssignableTo(NubTypeBool.Instance))
|
||||
throw BasicError("Condition part of if statement must be a boolean", condition);
|
||||
|
||||
var thenBlock = CheckStatement(statement.ThenBlock);
|
||||
var elseBlock = statement.ElseBlock == null ? null : CheckStatement(statement.ElseBlock);
|
||||
TypedNodeStatement thenBlock;
|
||||
|
||||
using (EnterScope())
|
||||
{
|
||||
thenBlock = CheckStatement(statement.ThenBlock);
|
||||
}
|
||||
|
||||
TypedNodeStatement? elseBlock;
|
||||
|
||||
using (EnterScope())
|
||||
{
|
||||
elseBlock = statement.ElseBlock == null ? null : CheckStatement(statement.ElseBlock);
|
||||
}
|
||||
|
||||
return new TypedNodeStatementIf(statement.Tokens, condition, thenBlock, elseBlock);
|
||||
}
|
||||
@@ -175,7 +187,7 @@ public class TypeChecker
|
||||
|
||||
type ??= value.Type;
|
||||
|
||||
scope.DeclareIdentifier(statement.Name.Ident, type);
|
||||
DeclareLocalIdentifier(statement.Name, type);
|
||||
|
||||
return new TypedNodeStatementVariableDeclaration(statement.Tokens, statement.Name, type, value);
|
||||
}
|
||||
@@ -186,10 +198,28 @@ public class TypeChecker
|
||||
if (!condition.Type.IsAssignableTo(NubTypeBool.Instance))
|
||||
throw BasicError("Condition part of if statement must be a boolean", condition);
|
||||
|
||||
using (EnterScope())
|
||||
{
|
||||
var body = CheckStatement(statement.Body);
|
||||
|
||||
return new TypedNodeStatementWhile(statement.Tokens, condition, body);
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
@@ -208,15 +238,24 @@ public class TypeChecker
|
||||
var cases = new List<TypedNodeStatementMatch.Case>();
|
||||
foreach (var @case in statement.Cases)
|
||||
{
|
||||
if (!enumInfo.Variants.Any(x => x.Name == @case.Variant.Ident))
|
||||
var variant = enumInfo.Variants.FirstOrDefault(x => x.Name == @case.Variant.Ident);
|
||||
if (variant == null)
|
||||
throw BasicError($"Enum type'{enumType}' does not have a variant named '{@case.Variant.Ident}'", @case.Variant);
|
||||
|
||||
uncoveredCases.Remove(@case.Variant.Ident);
|
||||
|
||||
using (scope.EnterScope())
|
||||
using (EnterScope())
|
||||
{
|
||||
scope.DeclareIdentifier(@case.VariableName.Ident, NubTypeEnumVariant.Get(NubTypeEnum.Get(enumType.Module, enumType.Name), @case.Variant.Ident));
|
||||
if (@case.VariableName != null)
|
||||
{
|
||||
if (variant.Type is null)
|
||||
throw BasicError("Cannot capture variable for enum variant without type", @case.VariableName);
|
||||
|
||||
DeclareLocalIdentifier(@case.VariableName, variant.Type);
|
||||
}
|
||||
|
||||
var body = CheckStatement(@case.Body);
|
||||
|
||||
cases.Add(new TypedNodeStatementMatch.Case(@case.Tokens, @case.Variant, @case.VariableName, body));
|
||||
}
|
||||
}
|
||||
@@ -241,6 +280,8 @@ public class TypeChecker
|
||||
NodeExpressionStringLiteral expression => CheckExpressionStringLiteral(expression, expectedType),
|
||||
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))
|
||||
};
|
||||
}
|
||||
@@ -255,6 +296,24 @@ public class TypeChecker
|
||||
switch (expression.Operation)
|
||||
{
|
||||
case NodeExpressionBinary.Op.Add:
|
||||
{
|
||||
if (left.Type is NubTypeString)
|
||||
{
|
||||
if (right.Type is not NubTypeString)
|
||||
throw BasicError("Right hand side of string concatination operator must be a string", right);
|
||||
|
||||
return new TypedNodeExpressionBinary(expression.Tokens, NubTypeString.Instance, left, CheckExpressionBinaryOperation(expression.Operation), right);
|
||||
}
|
||||
|
||||
if (left.Type is not NubTypeSInt and not NubTypeUInt)
|
||||
throw BasicError($"Unsupported type for left hand side arithmetic operation: {left.Type}", left);
|
||||
|
||||
if (right.Type is not NubTypeSInt and not NubTypeUInt)
|
||||
throw BasicError($"Unsupported type for right hand side arithmetic operation: {right.Type}", right);
|
||||
|
||||
type = left.Type;
|
||||
break;
|
||||
}
|
||||
case NodeExpressionBinary.Op.Subtract:
|
||||
case NodeExpressionBinary.Op.Multiply:
|
||||
case NodeExpressionBinary.Op.Divide:
|
||||
@@ -389,14 +448,14 @@ public class TypeChecker
|
||||
{
|
||||
if (expression.Sections.Count == 1)
|
||||
{
|
||||
var name = expression.Sections[0].Ident;
|
||||
var name = expression.Sections[0];
|
||||
|
||||
var localType = scope.GetIdentifierType(name);
|
||||
var localType = GetIdentifierType(name.Ident);
|
||||
if (localType is not null)
|
||||
return new TypedNodeExpressionLocalIdent(expression.Tokens, localType, name);
|
||||
return new TypedNodeExpressionLocalIdent(expression.Tokens, localType, name.Ident);
|
||||
|
||||
if (moduleGraph.TryResolveIdentifier(currentModule, name, true, out var ident))
|
||||
return new TypedNodeExpressionGlobalIdent(expression.Tokens, ident.Type, currentModule, name);
|
||||
if (moduleGraph.TryResolveIdentifier(currentModule, name.Ident, true, out var ident))
|
||||
return new TypedNodeExpressionGlobalIdent(expression.Tokens, ident.Type, currentModule, name.Ident);
|
||||
}
|
||||
else if (expression.Sections.Count == 2)
|
||||
{
|
||||
@@ -435,9 +494,21 @@ public class TypeChecker
|
||||
case "length":
|
||||
return new TypedNodeExpressionStringLength(expression.Tokens, NubTypeUInt.Get(64), target);
|
||||
case "ptr":
|
||||
return new TypedNodeExpressionStringPointer(expression.Tokens, NubTypePointer.Get(NubTypeUInt.Get(8)), target);
|
||||
return new TypedNodeExpressionStringPointer(expression.Tokens, NubTypePointer.Get(NubTypeChar.Instance), 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:
|
||||
@@ -600,10 +671,53 @@ public class TypeChecker
|
||||
if (variant == null)
|
||||
throw BasicError($"Enum '{variantType.EnumType}' does not have a variant named '{variantType.Variant}'", expression.Type);
|
||||
|
||||
var value = CheckExpression(expression.Value, variant.Type);
|
||||
if (expression.Value == null && variant.Type is not null)
|
||||
throw BasicError($"Enum variant '{variantType}' expects a value of type '{variant.Type}'", expression.Type);
|
||||
|
||||
if (expression.Value != null && variant.Type is null)
|
||||
throw BasicError($"Enum variant '{variantType}' does not expect any data", expression.Value);
|
||||
|
||||
var value = expression.Value == null ? null : CheckExpression(expression.Value, variant.Type);
|
||||
|
||||
return new TypedNodeExpressionEnumLiteral(expression.Tokens, type, value);
|
||||
}
|
||||
|
||||
private TypedNodeExpressionStringConstructor CheckExpressionStringConstructor(NodeExpressionStringConstructor expression, NubType? expectedType)
|
||||
{
|
||||
var stringPoitnerType = NubTypePointer.Get(NubTypeChar.Instance);
|
||||
|
||||
var value = CheckExpression(expression.Value, stringPoitnerType);
|
||||
if (!value.Type.IsAssignableTo(stringPoitnerType))
|
||||
throw BasicError($"Value of string constructor must be assignable to {stringPoitnerType}", value);
|
||||
|
||||
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
|
||||
@@ -617,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))
|
||||
};
|
||||
}
|
||||
@@ -721,19 +836,13 @@ public class TypeChecker
|
||||
return new CompileException(Diagnostic.Error(message).At(fileName, node).Build());
|
||||
}
|
||||
|
||||
private sealed class Scope
|
||||
public void DeclareLocalIdentifier(TokenIdent name, NubType type)
|
||||
{
|
||||
private readonly Stack<Dictionary<string, NubType>> scopes = new();
|
||||
var existing = GetIdentifierType(name.Ident);
|
||||
if (existing is not null)
|
||||
throw BasicError($"Local identifier '{name.Ident}' is already defined", name);
|
||||
|
||||
public IDisposable EnterScope()
|
||||
{
|
||||
scopes.Push([]);
|
||||
return new ScopeGuard(this);
|
||||
}
|
||||
|
||||
public void DeclareIdentifier(string name, NubType type)
|
||||
{
|
||||
scopes.Peek().Add(name, type);
|
||||
scopes.Peek().Add(name.Ident, type);
|
||||
}
|
||||
|
||||
public NubType? GetIdentifierType(string name)
|
||||
@@ -749,19 +858,24 @@ public class TypeChecker
|
||||
return null;
|
||||
}
|
||||
|
||||
public IDisposable EnterScope()
|
||||
{
|
||||
scopes.Push([]);
|
||||
return new ScopeGuard(this);
|
||||
}
|
||||
|
||||
private void ExitScope()
|
||||
{
|
||||
scopes.Pop();
|
||||
}
|
||||
|
||||
private sealed class ScopeGuard(Scope owner) : IDisposable
|
||||
private sealed class ScopeGuard(TypeChecker owner) : IDisposable
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
owner.ExitScope();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class TypedNode(List<Token> tokens)
|
||||
@@ -837,15 +951,22 @@ 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;
|
||||
public List<Case> Cases { get; } = cases;
|
||||
|
||||
public class Case(List<Token> tokens, TokenIdent type, TokenIdent variableName, TypedNodeStatement body) : Node(tokens)
|
||||
public class Case(List<Token> tokens, TokenIdent type, TokenIdent? variableName, TypedNodeStatement body) : Node(tokens)
|
||||
{
|
||||
public TokenIdent Variant { get; } = type;
|
||||
public TokenIdent VariableName { get; } = variableName;
|
||||
public TokenIdent? VariableName { get; } = variableName;
|
||||
public TypedNodeStatement Body { get; } = body;
|
||||
}
|
||||
}
|
||||
@@ -881,11 +1002,21 @@ public class TypedNodeExpressionStructLiteral(List<Token> tokens, NubType type,
|
||||
}
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionEnumLiteral(List<Token> tokens, NubType type, TypedNodeExpression value) : TypedNodeExpression(tokens, type)
|
||||
public class TypedNodeExpressionEnumLiteral(List<Token> tokens, NubType type, TypedNodeExpression? value) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
public TypedNodeExpression? Value { get; } = value;
|
||||
}
|
||||
|
||||
public class TypedNodeExpressionStringConstructor(List<Token> tokens, NubType type, TypedNodeExpression value) : TypedNodeExpression(tokens, type)
|
||||
{
|
||||
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;
|
||||
@@ -902,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;
|
||||
|
||||
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
|
||||
@@ -1,11 +0,0 @@
|
||||
set -e
|
||||
|
||||
pushd core
|
||||
dotnet run --project ../../compiler print.nub --type=lib
|
||||
popd
|
||||
|
||||
pushd program
|
||||
dotnet run --project ../../compiler main.nub ../core/.build/out.nublib
|
||||
popd
|
||||
|
||||
./program/.build/out
|
||||
@@ -1,7 +1,10 @@
|
||||
module core
|
||||
|
||||
extern func puts(text: ^u8)
|
||||
|
||||
export func print(text: string) {
|
||||
puts(text.ptr)
|
||||
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,25 +1,32 @@
|
||||
module main
|
||||
|
||||
extern func puts(text: ^u8)
|
||||
|
||||
export func print(text: string) {
|
||||
puts(text.ptr)
|
||||
struct Human {
|
||||
name: string
|
||||
age: i32
|
||||
}
|
||||
|
||||
enum Message {
|
||||
Tell: string
|
||||
Quit
|
||||
Say: string
|
||||
}
|
||||
|
||||
func main(): i32 {
|
||||
let x = "test"
|
||||
|
||||
let y = {
|
||||
abc = x
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let a: Message = enum Message::Tell x
|
||||
|
||||
core::print(x)
|
||||
|
||||
return 0
|
||||
}
|
||||
Reference in New Issue
Block a user