Compare commits
5 Commits
1511d5d2b8
...
282dd0502a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
282dd0502a | ||
|
|
3ebaa67b6d | ||
|
|
35867ffa28 | ||
|
|
76efc84984 | ||
|
|
583c01201f |
@@ -85,7 +85,7 @@ public class Generator
|
|||||||
case Module.TypeInfoEnum e:
|
case Module.TypeInfoEnum e:
|
||||||
{
|
{
|
||||||
writer.WriteLine();
|
writer.WriteLine();
|
||||||
writer.Write($"struct {NameMangler.Mangle(module.Name, name, NubTypeStruct.Get(module.Name, name))}");
|
writer.Write($"struct {NameMangler.Mangle(module.Name, name, NubTypeEnum.Get(module.Name, name))}");
|
||||||
writer.WriteLine("{");
|
writer.WriteLine("{");
|
||||||
using (writer.Indent())
|
using (writer.Indent())
|
||||||
{
|
{
|
||||||
@@ -96,7 +96,7 @@ public class Generator
|
|||||||
{
|
{
|
||||||
foreach (var variant in e.Variants)
|
foreach (var variant in e.Variants)
|
||||||
{
|
{
|
||||||
writer.WriteLine($"struct {variant.Name}");
|
writer.WriteLine("struct");
|
||||||
writer.WriteLine("{");
|
writer.WriteLine("{");
|
||||||
using (writer.Indent())
|
using (writer.Indent())
|
||||||
{
|
{
|
||||||
@@ -105,7 +105,7 @@ public class Generator
|
|||||||
writer.WriteLine($"{CType(field.Type, field.Name)};");
|
writer.WriteLine($"{CType(field.Type, field.Name)};");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writer.WriteLine("};");
|
writer.WriteLine($"}} {variant.Name};");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writer.WriteLine("};");
|
writer.WriteLine("};");
|
||||||
@@ -165,7 +165,7 @@ 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.Kind == Module.DefinitionKind.Internal)
|
if (info.Kind == Module.DefinitionKind.Internal)
|
||||||
writer.Write("static ");
|
writer.Write("static ");
|
||||||
|
|
||||||
@@ -209,6 +209,9 @@ public class Generator
|
|||||||
case TypedNodeStatementWhile statement:
|
case TypedNodeStatementWhile statement:
|
||||||
EmitStatementWhile(statement);
|
EmitStatementWhile(statement);
|
||||||
break;
|
break;
|
||||||
|
case TypedNodeStatementMatch statement:
|
||||||
|
EmitStatementMatch(statement);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
throw new ArgumentOutOfRangeException(nameof(node), node, null);
|
throw new ArgumentOutOfRangeException(nameof(node), node, null);
|
||||||
}
|
}
|
||||||
@@ -286,7 +289,38 @@ public class Generator
|
|||||||
writer.WriteLine("{");
|
writer.WriteLine("{");
|
||||||
using (writer.Indent())
|
using (writer.Indent())
|
||||||
{
|
{
|
||||||
EmitStatement(statement.Block);
|
EmitStatement(statement.Body);
|
||||||
|
}
|
||||||
|
writer.WriteLine("}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EmitStatementMatch(TypedNodeStatementMatch statement)
|
||||||
|
{
|
||||||
|
var target = EmitExpression(statement.Target);
|
||||||
|
var enumType = (NubTypeEnum)statement.Target.Type;
|
||||||
|
|
||||||
|
if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info))
|
||||||
|
throw new UnreachableException();
|
||||||
|
|
||||||
|
var enumInfo = (Module.TypeInfoEnum)info;
|
||||||
|
|
||||||
|
writer.WriteLine($"switch ({target}.tag)");
|
||||||
|
writer.WriteLine("{");
|
||||||
|
using (writer.Indent())
|
||||||
|
{
|
||||||
|
foreach (var @case in statement.Cases)
|
||||||
|
{
|
||||||
|
var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == @case.Type.Ident);
|
||||||
|
|
||||||
|
writer.WriteLine($"case {tag}:");
|
||||||
|
writer.WriteLine("{");
|
||||||
|
using (writer.Indent())
|
||||||
|
{
|
||||||
|
writer.WriteLine($"auto {@case.VariableName.Ident} = {target}.{@case.Type.Ident};");
|
||||||
|
EmitStatement(@case.Body);
|
||||||
|
}
|
||||||
|
writer.WriteLine("}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
writer.WriteLine("}");
|
writer.WriteLine("}");
|
||||||
}
|
}
|
||||||
@@ -301,6 +335,7 @@ public class Generator
|
|||||||
TypedNodeExpressionIntLiteral expression => expression.Value.Value.ToString(),
|
TypedNodeExpressionIntLiteral expression => expression.Value.Value.ToString(),
|
||||||
TypedNodeExpressionStringLiteral expression => $"(struct nub_core_string){{ \"{expression.Value.Value}\", {expression.Value.Value.Length} }}",
|
TypedNodeExpressionStringLiteral expression => $"(struct nub_core_string){{ \"{expression.Value.Value}\", {expression.Value.Value.Length} }}",
|
||||||
TypedNodeExpressionStructLiteral expression => EmitExpressionStructLiteral(expression),
|
TypedNodeExpressionStructLiteral expression => EmitExpressionStructLiteral(expression),
|
||||||
|
TypedNodeExpressionEnumLiteral expression => EmitExpressionEnumLiteral(expression),
|
||||||
TypedNodeExpressionMemberAccess expression => EmitExpressionMemberAccess(expression),
|
TypedNodeExpressionMemberAccess expression => EmitExpressionMemberAccess(expression),
|
||||||
TypedNodeExpressionLocalIdent expression => expression.Value.Ident,
|
TypedNodeExpressionLocalIdent expression => expression.Value.Ident,
|
||||||
TypedNodeExpressionModuleIdent expression => EmitExpressionModuleIdent(expression),
|
TypedNodeExpressionModuleIdent expression => EmitExpressionModuleIdent(expression),
|
||||||
@@ -362,6 +397,29 @@ public class Generator
|
|||||||
return $"({CType(expression.Type)}){{ {string.Join(", ", initializerStrings)} }}";
|
return $"({CType(expression.Type)}){{ {string.Join(", ", initializerStrings)} }}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string EmitExpressionEnumLiteral(TypedNodeExpressionEnumLiteral expression)
|
||||||
|
{
|
||||||
|
var enumVariantType = (NubTypeEnumVariant)expression.Type;
|
||||||
|
|
||||||
|
if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info))
|
||||||
|
throw new UnreachableException();
|
||||||
|
|
||||||
|
var enumInfo = (Module.TypeInfoEnum)info;
|
||||||
|
var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == enumVariantType.Variant);
|
||||||
|
|
||||||
|
var initializerValues = new Dictionary<string, string>();
|
||||||
|
|
||||||
|
foreach (var initializer in expression.Initializers)
|
||||||
|
{
|
||||||
|
var values = EmitExpression(initializer.Value);
|
||||||
|
initializerValues[initializer.Name.Ident] = values;
|
||||||
|
}
|
||||||
|
|
||||||
|
var initializerStrings = initializerValues.Select(x => $".{x.Key} = {x.Value}");
|
||||||
|
|
||||||
|
return $"({CType(expression.Type)}){{ .tag = {tag}, .{enumVariantType.Variant} = {{ {string.Join(", ", initializerStrings)} }} }}";
|
||||||
|
}
|
||||||
|
|
||||||
private string EmitExpressionMemberAccess(TypedNodeExpressionMemberAccess expression)
|
private string EmitExpressionMemberAccess(TypedNodeExpressionMemberAccess expression)
|
||||||
{
|
{
|
||||||
var target = EmitExpression(expression.Target);
|
var target = EmitExpression(expression.Target);
|
||||||
@@ -390,6 +448,8 @@ public class Generator
|
|||||||
NubTypeVoid => "void" + (varName != null ? $" {varName}" : ""),
|
NubTypeVoid => "void" + (varName != null ? $" {varName}" : ""),
|
||||||
NubTypeBool => "bool" + (varName != null ? $" {varName}" : ""),
|
NubTypeBool => "bool" + (varName != null ? $" {varName}" : ""),
|
||||||
NubTypeStruct type => $"struct {NameMangler.Mangle(type.Module, type.Name, type)}" + (varName != null ? $" {varName}" : ""),
|
NubTypeStruct type => $"struct {NameMangler.Mangle(type.Module, type.Name, type)}" + (varName != null ? $" {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}" : ""),
|
NubTypeSInt type => $"int{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
||||||
NubTypeUInt type => $"uint{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
NubTypeUInt type => $"uint{type.Width}_t" + (varName != null ? $" {varName}" : ""),
|
||||||
NubTypePointer type => CType(type.To) + (varName != null ? $" *{varName}" : "*"),
|
NubTypePointer type => CType(type.To) + (varName != null ? $" *{varName}" : "*"),
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ public class ModuleGraph
|
|||||||
return node switch
|
return node switch
|
||||||
{
|
{
|
||||||
NodeTypeBool => NubTypeBool.Instance,
|
NodeTypeBool => NubTypeBool.Instance,
|
||||||
NodeTypeCustom type => ResolveCustomType(type, currentModule),
|
NodeTypeNamed type => ResolveNamedType(type, currentModule),
|
||||||
NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(x => ResolveType(x, currentModule)).ToList(), ResolveType(type.ReturnType, currentModule)),
|
NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(x => ResolveType(x, currentModule)).ToList(), ResolveType(type.ReturnType, currentModule)),
|
||||||
NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To, currentModule)),
|
NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To, currentModule)),
|
||||||
NodeTypeSInt type => NubTypeSInt.Get(type.Width),
|
NodeTypeSInt type => NubTypeSInt.Get(type.Width),
|
||||||
@@ -202,25 +202,103 @@ public class ModuleGraph
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
NubType ResolveCustomType(NodeTypeCustom type, string currentModule)
|
NubType ResolveNamedType(NodeTypeNamed type, string currentModule)
|
||||||
{
|
{
|
||||||
var module = modules.GetValueOrDefault(type.Module.Ident);
|
return type.Sections.Count switch
|
||||||
if (module == null)
|
|
||||||
throw new CompileException(Diagnostic.Error($"Unknown module: {type.Module.Ident}").Build());
|
|
||||||
|
|
||||||
var includePrivate = currentModule == type.Module.Ident;
|
|
||||||
|
|
||||||
if (!module.TryResolveType(type.Name.Ident, includePrivate, out var customType))
|
|
||||||
throw new CompileException(Diagnostic.Error($"Unknown custom type: {type.Module.Ident}::{type.Name.Ident}").Build());
|
|
||||||
|
|
||||||
return customType switch
|
|
||||||
{
|
{
|
||||||
Module.TypeInfoStruct => NubTypeStruct.Get(type.Module.Ident, type.Name.Ident),
|
3 => ResolveThreePartType(type.Sections[0], type.Sections[1], type.Sections[2], currentModule),
|
||||||
Module.TypeInfoEnum => NubTypeEnum.Get(type.Module.Ident, type.Name.Ident),
|
2 => ResolveTwoPartType(type.Sections[0], type.Sections[1], currentModule),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(customType))
|
1 => ResolveOnePartType(type.Sections[0], currentModule),
|
||||||
|
_ => throw BasicError("Invalid type name")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
NubType ResolveThreePartType(TokenIdent first, TokenIdent second, TokenIdent third, string currentModule)
|
||||||
|
{
|
||||||
|
var module = ResolveModule(first);
|
||||||
|
if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo))
|
||||||
|
throw BasicError($"Named type '{module.Name}::{second.Ident}' not found");
|
||||||
|
|
||||||
|
if (typeInfo is not Module.TypeInfoEnum enumInfo)
|
||||||
|
throw BasicError($"'{module.Name}::{second.Ident}' is not an enum");
|
||||||
|
|
||||||
|
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == third.Ident);
|
||||||
|
if (variant == null)
|
||||||
|
throw BasicError($"Enum '{module.Name}::{second.Ident}' does not have a variant named '{third.Ident}'");
|
||||||
|
|
||||||
|
return NubTypeEnumVariant.Get(NubTypeEnum.Get(module.Name, second.Ident), third.Ident);
|
||||||
|
}
|
||||||
|
|
||||||
|
NubType ResolveTwoPartType(TokenIdent first, TokenIdent second, string currentModule)
|
||||||
|
{
|
||||||
|
if (TryResolveEnumVariant(currentModule, first.Ident, second.Ident, out var variant))
|
||||||
|
return variant;
|
||||||
|
|
||||||
|
var module = ResolveModule(first);
|
||||||
|
if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo))
|
||||||
|
throw BasicError($"Named type '{module.Name}::{second.Ident}' not found");
|
||||||
|
|
||||||
|
return typeInfo switch
|
||||||
|
{
|
||||||
|
Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, second.Ident),
|
||||||
|
Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, second.Ident),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
NubType ResolveOnePartType(TokenIdent name, string currentModule)
|
||||||
|
{
|
||||||
|
if (!modules.TryGetValue(currentModule, out var module))
|
||||||
|
throw BasicError($"Module '{currentModule}' not found");
|
||||||
|
|
||||||
|
if (!module.TryResolveType(name.Ident, true, out var typeInfo))
|
||||||
|
throw BasicError($"Named type '{module.Name}::{name.Ident}' not found");
|
||||||
|
|
||||||
|
return typeInfo switch
|
||||||
|
{
|
||||||
|
Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, name.Ident),
|
||||||
|
Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, name.Ident),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Module ResolveModule(TokenIdent name)
|
||||||
|
{
|
||||||
|
if (!modules.TryGetValue(name.Ident, out var module))
|
||||||
|
throw BasicError($"Module '{name.Ident}' not found");
|
||||||
|
|
||||||
|
return module;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TryResolveEnumVariant(string moduleName, string enumName, string variantName, [NotNullWhen(true)] out NubType? result)
|
||||||
|
{
|
||||||
|
result = null;
|
||||||
|
|
||||||
|
if (!modules.TryGetValue(moduleName, out var module))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!module.TryResolveType(enumName, true, out var typeInfo))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (typeInfo is not Module.TypeInfoEnum enumInfo)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == variantName);
|
||||||
|
if (variant == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
result = NubTypeEnumVariant.Get(
|
||||||
|
NubTypeEnum.Get(moduleName, enumName),
|
||||||
|
variantName);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Exception BasicError(string message)
|
||||||
|
{
|
||||||
|
return new CompileException(Diagnostic.Error(message).Build());
|
||||||
|
}
|
||||||
|
|
||||||
Module GetOrCreateModule(string name)
|
Module GetOrCreateModule(string name)
|
||||||
{
|
{
|
||||||
if (!modules.TryGetValue(name, out var module))
|
if (!modules.TryGetValue(name, out var module))
|
||||||
|
|||||||
@@ -8,6 +8,21 @@ namespace Compiler;
|
|||||||
public abstract class NubType
|
public abstract class NubType
|
||||||
{
|
{
|
||||||
public abstract override string ToString();
|
public abstract override string ToString();
|
||||||
|
|
||||||
|
[Obsolete("Use IsAssignableTo instead of ==", error: true)]
|
||||||
|
public static bool operator ==(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo");
|
||||||
|
|
||||||
|
[Obsolete("Use IsAssignableTo instead of ==", error: true)]
|
||||||
|
public static bool operator !=(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo");
|
||||||
|
|
||||||
|
public bool IsAssignableTo(NubType target)
|
||||||
|
{
|
||||||
|
return (this, target) switch
|
||||||
|
{
|
||||||
|
(NubTypeEnumVariant variant, NubTypeEnum targetEnum) => ReferenceEquals(variant.EnumType, targetEnum),
|
||||||
|
_ => ReferenceEquals(this, target),
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class NubTypeVoid : NubType
|
public class NubTypeVoid : NubType
|
||||||
@@ -135,6 +150,30 @@ public class NubTypeEnum : NubType
|
|||||||
public override string ToString() => $"enum {Module}::{Name}";
|
public override string ToString() => $"enum {Module}::{Name}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class NubTypeEnumVariant : NubType
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<(NubTypeEnum EnumType, string Variant), NubTypeEnumVariant> Cache = new();
|
||||||
|
|
||||||
|
public static NubTypeEnumVariant Get(NubTypeEnum enumType, string variant)
|
||||||
|
{
|
||||||
|
if (!Cache.TryGetValue((enumType, variant), out var variantType))
|
||||||
|
Cache[(enumType, variant)] = variantType = new NubTypeEnumVariant(enumType, variant);
|
||||||
|
|
||||||
|
return variantType;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NubTypeEnumVariant(NubTypeEnum enumType, string variant)
|
||||||
|
{
|
||||||
|
EnumType = enumType;
|
||||||
|
Variant = variant;
|
||||||
|
}
|
||||||
|
|
||||||
|
public NubTypeEnum EnumType { get; }
|
||||||
|
public string Variant { get; }
|
||||||
|
|
||||||
|
public override string ToString() => $"{EnumType}.{Variant}";
|
||||||
|
}
|
||||||
|
|
||||||
public class NubTypePointer : NubType
|
public class NubTypePointer : NubType
|
||||||
{
|
{
|
||||||
private static readonly Dictionary<NubType, NubTypePointer> Cache = new();
|
private static readonly Dictionary<NubType, NubTypePointer> Cache = new();
|
||||||
@@ -245,11 +284,21 @@ public class TypeEncoder
|
|||||||
sb.Append(')');
|
sb.Append(')');
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case NubTypeEnum st:
|
case NubTypeEnum e:
|
||||||
sb.Append("E(");
|
sb.Append("EN(");
|
||||||
sb.Append(st.Module);
|
sb.Append(e.Module);
|
||||||
sb.Append(':');
|
sb.Append(':');
|
||||||
sb.Append(st.Name);
|
sb.Append(e.Name);
|
||||||
|
sb.Append(')');
|
||||||
|
break;
|
||||||
|
|
||||||
|
case NubTypeEnumVariant ev:
|
||||||
|
sb.Append("EV(");
|
||||||
|
sb.Append(ev.EnumType.Module);
|
||||||
|
sb.Append(':');
|
||||||
|
sb.Append(ev.EnumType.Name);
|
||||||
|
sb.Append(':');
|
||||||
|
sb.Append(ev.Variant);
|
||||||
sb.Append(')');
|
sb.Append(')');
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -364,23 +413,49 @@ public class TypeDecoder
|
|||||||
return NubTypeStruct.Get(module, name);
|
return NubTypeStruct.Get(module, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
private NubTypeEnum DecodeEnum()
|
private NubType DecodeEnum()
|
||||||
{
|
{
|
||||||
var sb = new StringBuilder();
|
var sb = new StringBuilder();
|
||||||
|
|
||||||
Expect('(');
|
if (TryExpect('V'))
|
||||||
while (!TryExpect(':'))
|
{
|
||||||
sb.Append(Consume());
|
Expect('(');
|
||||||
|
while (!TryExpect(':'))
|
||||||
|
sb.Append(Consume());
|
||||||
|
|
||||||
var module = sb.ToString();
|
var module = sb.ToString();
|
||||||
sb.Clear();
|
sb.Clear();
|
||||||
|
|
||||||
while (!TryExpect(')'))
|
while (!TryExpect(':'))
|
||||||
sb.Append(Consume());
|
sb.Append(Consume());
|
||||||
|
|
||||||
var name = sb.ToString();
|
var name = sb.ToString();
|
||||||
|
|
||||||
return NubTypeEnum.Get(module, name);
|
while (!TryExpect(')'))
|
||||||
|
sb.Append(Consume());
|
||||||
|
|
||||||
|
var variant = sb.ToString();
|
||||||
|
|
||||||
|
return NubTypeEnumVariant.Get(NubTypeEnum.Get(module, name), variant);
|
||||||
|
}
|
||||||
|
else if (TryExpect('N'))
|
||||||
|
{
|
||||||
|
Expect('(');
|
||||||
|
while (!TryExpect(':'))
|
||||||
|
sb.Append(Consume());
|
||||||
|
|
||||||
|
var module = sb.ToString();
|
||||||
|
sb.Clear();
|
||||||
|
|
||||||
|
while (!TryExpect(')'))
|
||||||
|
sb.Append(Consume());
|
||||||
|
|
||||||
|
var name = sb.ToString();
|
||||||
|
|
||||||
|
return NubTypeEnum.Get(module, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Exception($"Expected 'V' or 'N'");
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool TryPeek(out char c)
|
private bool TryPeek(out char c)
|
||||||
|
|||||||
@@ -243,9 +243,10 @@ public class Parser
|
|||||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||||
{
|
{
|
||||||
var caseStartIndex = index;
|
var caseStartIndex = index;
|
||||||
var name = ExpectIdent();
|
var type = ExpectIdent();
|
||||||
|
var variableName = ExpectIdent();
|
||||||
var body = ParseStatement();
|
var body = ParseStatement();
|
||||||
cases.Add(new NodeStatementMatch.Case(TokensFrom(caseStartIndex), name, body));
|
cases.Add(new NodeStatementMatch.Case(TokensFrom(caseStartIndex), type, variableName, body));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new NodeStatementMatch(TokensFrom(startIndex), target, cases);
|
return new NodeStatementMatch(TokensFrom(startIndex), target, cases);
|
||||||
@@ -378,6 +379,28 @@ public class Parser
|
|||||||
|
|
||||||
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), module, name, initializers);
|
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), module, name, initializers);
|
||||||
}
|
}
|
||||||
|
else if (TryExpectKeyword(Keyword.Enum))
|
||||||
|
{
|
||||||
|
var module = ExpectIdent();
|
||||||
|
ExpectSymbol(Symbol.ColonColon);
|
||||||
|
var enumName = ExpectIdent();
|
||||||
|
ExpectSymbol(Symbol.ColonColon);
|
||||||
|
var variantName = ExpectIdent();
|
||||||
|
|
||||||
|
var initializers = new List<NodeExpressionEnumLiteral.Initializer>();
|
||||||
|
|
||||||
|
ExpectSymbol(Symbol.OpenCurly);
|
||||||
|
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||||
|
{
|
||||||
|
var initializerStartIndex = startIndex;
|
||||||
|
var fieldName = ExpectIdent();
|
||||||
|
ExpectSymbol(Symbol.Equal);
|
||||||
|
var fieldValue = ParseExpression();
|
||||||
|
initializers.Add(new NodeExpressionEnumLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), module, enumName, variantName, initializers);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new CompileException(Diagnostic.Error("Expected start of expression").At(fileName, Peek()).Build());
|
throw new CompileException(Diagnostic.Error("Expected start of expression").At(fileName, Peek()).Build());
|
||||||
@@ -461,9 +484,14 @@ public class Parser
|
|||||||
case "u64":
|
case "u64":
|
||||||
return new NodeTypeUInt(TokensFrom(startIndex), 64);
|
return new NodeTypeUInt(TokensFrom(startIndex), 64);
|
||||||
default:
|
default:
|
||||||
ExpectSymbol(Symbol.ColonColon);
|
List<TokenIdent> secitons = [ident];
|
||||||
var name = ExpectIdent();
|
while (TryExpectSymbol(Symbol.ColonColon))
|
||||||
return new NodeTypeCustom(TokensFrom(startIndex), ident, name);
|
{
|
||||||
|
ident = ExpectIdent();
|
||||||
|
secitons.Add(ident);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new NodeTypeNamed(TokensFrom(startIndex), secitons);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -766,10 +794,10 @@ public class NodeStatementIf(List<Token> tokens, NodeExpression condition, NodeS
|
|||||||
public NodeStatement? ElseBlock { get; } = elseBlock;
|
public NodeStatement? ElseBlock { get; } = elseBlock;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class NodeStatementWhile(List<Token> tokens, NodeExpression condition, NodeStatement block) : NodeStatement(tokens)
|
public class NodeStatementWhile(List<Token> tokens, NodeExpression condition, NodeStatement body) : NodeStatement(tokens)
|
||||||
{
|
{
|
||||||
public NodeExpression Condition { get; } = condition;
|
public NodeExpression Condition { get; } = condition;
|
||||||
public NodeStatement Block { get; } = block;
|
public NodeStatement Body { get; } = body;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class NodeStatementMatch(List<Token> tokens, NodeExpression target, List<NodeStatementMatch.Case> cases) : NodeStatement(tokens)
|
public class NodeStatementMatch(List<Token> tokens, NodeExpression target, List<NodeStatementMatch.Case> cases) : NodeStatement(tokens)
|
||||||
@@ -777,10 +805,11 @@ public class NodeStatementMatch(List<Token> tokens, NodeExpression target, List<
|
|||||||
public NodeExpression Target { get; } = target;
|
public NodeExpression Target { get; } = target;
|
||||||
public List<Case> Cases { get; } = cases;
|
public List<Case> Cases { get; } = cases;
|
||||||
|
|
||||||
public class Case(List<Token> tokens, TokenIdent type, NodeStatement block) : Node(tokens)
|
public class Case(List<Token> tokens, TokenIdent type, TokenIdent variableName, NodeStatement body) : Node(tokens)
|
||||||
{
|
{
|
||||||
public TokenIdent Type { get; } = type;
|
public TokenIdent Variant { get; } = type;
|
||||||
public NodeStatement Block { get; } = block;
|
public TokenIdent VariableName { get; } = variableName;
|
||||||
|
public NodeStatement Body { get; } = body;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -814,6 +843,20 @@ public class NodeExpressionStructLiteral(List<Token> tokens, TokenIdent module,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class NodeExpressionEnumLiteral(List<Token> tokens, TokenIdent module, TokenIdent enumName, TokenIdent variantName, List<NodeExpressionEnumLiteral.Initializer> initializers) : NodeExpression(tokens)
|
||||||
|
{
|
||||||
|
public TokenIdent Module { get; } = module;
|
||||||
|
public TokenIdent EnumName { get; } = enumName;
|
||||||
|
public TokenIdent VariantName { get; } = variantName;
|
||||||
|
public List<Initializer> Initializers { get; } = initializers;
|
||||||
|
|
||||||
|
public class Initializer(List<Token> tokens, TokenIdent name, NodeExpression value) : Node(tokens)
|
||||||
|
{
|
||||||
|
public TokenIdent Name { get; } = name;
|
||||||
|
public NodeExpression Value { get; } = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public class NodeExpressionMemberAccess(List<Token> tokens, NodeExpression target, TokenIdent name) : NodeExpression(tokens)
|
public class NodeExpressionMemberAccess(List<Token> tokens, NodeExpression target, TokenIdent name) : NodeExpression(tokens)
|
||||||
{
|
{
|
||||||
public NodeExpression Target { get; } = target;
|
public NodeExpression Target { get; } = target;
|
||||||
@@ -900,10 +943,9 @@ 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 NodeTypeCustom(List<Token> tokens, TokenIdent module, TokenIdent name) : NodeType(tokens)
|
public class NodeTypeNamed(List<Token> tokens, List<TokenIdent> sections) : NodeType(tokens)
|
||||||
{
|
{
|
||||||
public TokenIdent Module { get; } = module;
|
public List<TokenIdent> Sections { get; } = sections;
|
||||||
public TokenIdent Name { get; } = name;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class NodeTypePointer(List<Token> tokens, NodeType to) : NodeType(tokens)
|
public class NodeTypePointer(List<Token> tokens, NodeType to) : NodeType(tokens)
|
||||||
|
|||||||
@@ -1,22 +1,25 @@
|
|||||||
namespace Compiler;
|
using System.Data.Common;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
|
||||||
|
namespace Compiler;
|
||||||
|
|
||||||
public class TypeChecker
|
public class TypeChecker
|
||||||
{
|
{
|
||||||
public static TypedNodeDefinitionFunc? CheckFunction(string fileName, string moduleName, NodeDefinitionFunc function, ModuleGraph moduleGraph, out List<Diagnostic> diagnostics)
|
public static TypedNodeDefinitionFunc? CheckFunction(string fileName, string currentModule, NodeDefinitionFunc function, ModuleGraph moduleGraph, out List<Diagnostic> diagnostics)
|
||||||
{
|
{
|
||||||
return new TypeChecker(fileName, moduleName, function, moduleGraph).CheckFunction(out diagnostics);
|
return new TypeChecker(fileName, currentModule, function, moduleGraph).CheckFunction(out diagnostics);
|
||||||
}
|
}
|
||||||
|
|
||||||
private TypeChecker(string fileName, string moduleName, NodeDefinitionFunc function, ModuleGraph moduleGraph)
|
private TypeChecker(string fileName, string currentModule, NodeDefinitionFunc function, ModuleGraph moduleGraph)
|
||||||
{
|
{
|
||||||
this.fileName = fileName;
|
this.fileName = fileName;
|
||||||
this.moduleName = moduleName;
|
this.currentModule = currentModule;
|
||||||
this.function = function;
|
this.function = function;
|
||||||
this.moduleGraph = moduleGraph;
|
this.moduleGraph = moduleGraph;
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly string fileName;
|
private readonly string fileName;
|
||||||
private readonly string moduleName;
|
private readonly string currentModule;
|
||||||
private readonly NodeDefinitionFunc function;
|
private readonly NodeDefinitionFunc function;
|
||||||
private readonly ModuleGraph moduleGraph;
|
private readonly ModuleGraph moduleGraph;
|
||||||
private readonly Scope scope = new();
|
private readonly Scope scope = new();
|
||||||
@@ -69,10 +72,10 @@ public class TypeChecker
|
|||||||
diagnostics.Add(e.Diagnostic);
|
diagnostics.Add(e.Diagnostic);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body == null || returnType == null || invalidParameter)
|
if (body == null || returnType is null || invalidParameter)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
return new TypedNodeDefinitionFunc(function.Tokens, moduleName, function.Name, parameters, body, returnType);
|
return new TypedNodeDefinitionFunc(function.Tokens, currentModule, function.Name, parameters, body, returnType);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,6 +90,7 @@ public class TypeChecker
|
|||||||
NodeStatementReturn statement => CheckStatementReturn(statement),
|
NodeStatementReturn statement => CheckStatementReturn(statement),
|
||||||
NodeStatementVariableDeclaration statement => CheckStatementVariableDeclaration(statement),
|
NodeStatementVariableDeclaration statement => CheckStatementVariableDeclaration(statement),
|
||||||
NodeStatementWhile statement => CheckStatementWhile(statement),
|
NodeStatementWhile statement => CheckStatementWhile(statement),
|
||||||
|
NodeStatementMatch statement => CheckStatementMatch(statement),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -128,7 +132,7 @@ public class TypeChecker
|
|||||||
var type = ResolveType(statement.Type);
|
var type = ResolveType(statement.Type);
|
||||||
var value = CheckExpression(statement.Value);
|
var value = CheckExpression(statement.Value);
|
||||||
|
|
||||||
if (type != value.Type)
|
if (!value.Type.IsAssignableTo(type))
|
||||||
throw new CompileException(Diagnostic.Error("Type of variable does match type of assigned value").At(fileName, value).Build());
|
throw new CompileException(Diagnostic.Error("Type of variable does match type of assigned value").At(fileName, value).Build());
|
||||||
|
|
||||||
scope.DeclareIdentifier(statement.Name.Ident, type);
|
scope.DeclareIdentifier(statement.Name.Ident, type);
|
||||||
@@ -138,7 +142,26 @@ public class TypeChecker
|
|||||||
|
|
||||||
private TypedNodeStatementWhile CheckStatementWhile(NodeStatementWhile statement)
|
private TypedNodeStatementWhile CheckStatementWhile(NodeStatementWhile statement)
|
||||||
{
|
{
|
||||||
return new TypedNodeStatementWhile(statement.Tokens, CheckExpression(statement.Condition), CheckStatement(statement.Block));
|
return new TypedNodeStatementWhile(statement.Tokens, CheckExpression(statement.Condition), CheckStatement(statement.Body));
|
||||||
|
}
|
||||||
|
|
||||||
|
private TypedNodeStatementMatch CheckStatementMatch(NodeStatementMatch statement)
|
||||||
|
{
|
||||||
|
var cases = new List<TypedNodeStatementMatch.Case>();
|
||||||
|
var target = CheckExpression(statement.Target);
|
||||||
|
var enumType = (NubTypeEnum)target.Type;
|
||||||
|
|
||||||
|
foreach (var @case in statement.Cases)
|
||||||
|
{
|
||||||
|
using (scope.EnterScope())
|
||||||
|
{
|
||||||
|
scope.DeclareIdentifier(@case.VariableName.Ident, NubTypeEnumVariant.Get(NubTypeEnum.Get(enumType.Module, enumType.Name), @case.Variant.Ident));
|
||||||
|
var body = CheckStatement(@case.Body);
|
||||||
|
cases.Add(new TypedNodeStatementMatch.Case(@case.Tokens, @case.Variant, @case.VariableName, body));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TypedNodeStatementMatch(statement.Tokens, target, cases);
|
||||||
}
|
}
|
||||||
|
|
||||||
private TypedNodeExpression CheckExpression(NodeExpression node)
|
private TypedNodeExpression CheckExpression(NodeExpression node)
|
||||||
@@ -155,6 +178,7 @@ public class TypeChecker
|
|||||||
NodeExpressionFuncCall expression => CheckExpressionFuncCall(expression),
|
NodeExpressionFuncCall expression => CheckExpressionFuncCall(expression),
|
||||||
NodeExpressionStringLiteral expression => CheckExpressionStringLiteral(expression),
|
NodeExpressionStringLiteral expression => CheckExpressionStringLiteral(expression),
|
||||||
NodeExpressionStructLiteral expression => CheckExpressionStructLiteral(expression),
|
NodeExpressionStructLiteral expression => CheckExpressionStructLiteral(expression),
|
||||||
|
NodeExpressionEnumLiteral expression => CheckExpressionEnumLiteral(expression),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -300,7 +324,7 @@ public class TypeChecker
|
|||||||
private TypedNodeExpressionLocalIdent CheckExpressionIdent(NodeExpressionLocalIdent expression)
|
private TypedNodeExpressionLocalIdent CheckExpressionIdent(NodeExpressionLocalIdent expression)
|
||||||
{
|
{
|
||||||
var type = scope.GetIdentifierType(expression.Value.Ident);
|
var type = scope.GetIdentifierType(expression.Value.Ident);
|
||||||
if (type == null)
|
if (type is null)
|
||||||
throw new CompileException(Diagnostic.Error($"Identifier '{expression.Value.Ident}' is not declared").At(fileName, expression.Value).Build());
|
throw new CompileException(Diagnostic.Error($"Identifier '{expression.Value.Ident}' is not declared").At(fileName, expression.Value).Build());
|
||||||
|
|
||||||
return new TypedNodeExpressionLocalIdent(expression.Tokens, type, expression.Value);
|
return new TypedNodeExpressionLocalIdent(expression.Tokens, type, expression.Value);
|
||||||
@@ -308,15 +332,9 @@ public class TypeChecker
|
|||||||
|
|
||||||
private TypedNodeExpressionModuleIdent CheckExpressionModuleIdent(NodeExpressionModuleIdent expression)
|
private TypedNodeExpressionModuleIdent CheckExpressionModuleIdent(NodeExpressionModuleIdent expression)
|
||||||
{
|
{
|
||||||
if (!moduleGraph.TryResolveModule(expression.Module.Ident, out var module))
|
var module = ResolveModule(expression.Module);
|
||||||
throw new CompileException(Diagnostic.Error($"Module '{expression.Module.Ident}' not found").At(fileName, expression.Module).Build());
|
var info = ResolveModuleIdentifier(module, expression.Value);
|
||||||
|
return new TypedNodeExpressionModuleIdent(expression.Tokens, info.Type, expression.Module, expression.Value);
|
||||||
var includePrivate = expression.Module.Ident == moduleName;
|
|
||||||
|
|
||||||
if (!module.TryResolveIdentifier(expression.Value.Ident, includePrivate, out var identifierType))
|
|
||||||
throw new CompileException(Diagnostic.Error($"Identifier '{expression.Module.Ident}::{expression.Value.Ident}' not found").At(fileName, expression.Value).Build());
|
|
||||||
|
|
||||||
return new TypedNodeExpressionModuleIdent(expression.Tokens, identifierType.Type, expression.Module, expression.Value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private TypedNodeExpressionIntLiteral CheckExpressionIntLiteral(NodeExpressionIntLiteral expression)
|
private TypedNodeExpressionIntLiteral CheckExpressionIntLiteral(NodeExpressionIntLiteral expression)
|
||||||
@@ -331,20 +349,43 @@ public class TypeChecker
|
|||||||
switch (target.Type)
|
switch (target.Type)
|
||||||
{
|
{
|
||||||
case NubTypeStruct structType:
|
case NubTypeStruct structType:
|
||||||
|
{
|
||||||
if (!moduleGraph.TryResolveModule(structType.Module, out var module))
|
if (!moduleGraph.TryResolveModule(structType.Module, out var module))
|
||||||
throw new CompileException(Diagnostic.Error($"Module '{structType.Module}' not found").At(fileName, expression.Target).Build());
|
throw new CompileException(Diagnostic.Error($"Module '{structType.Module}' not found").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
if (!module.TryResolveType(structType.Name, moduleName == structType.Module, out var typeDef))
|
if (!module.TryResolveType(structType.Name, currentModule == structType.Module, out var typeDef))
|
||||||
throw new CompileException(Diagnostic.Error($"Type '{structType.Name}' not found in module '{structType.Module}'").At(fileName, expression.Target).Build());
|
throw new CompileException(Diagnostic.Error($"Type '{structType.Name}' not found in module '{structType.Module}'").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
if (typeDef is not Module.TypeInfoStruct structDef)
|
if (typeDef is not Module.TypeInfoStruct structDef)
|
||||||
throw new CompileException(Diagnostic.Error($"Type '{structType.Module}::{structType.Name}' is not a struct").At(fileName, expression.Target).Build());
|
throw new CompileException(Diagnostic.Error($"Type '{target.Type}' is not a struct").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
var field = structDef.Fields.FirstOrDefault(x => x.Name == expression.Name.Ident);
|
var field = structDef.Fields.FirstOrDefault(x => x.Name == expression.Name.Ident);
|
||||||
if (field == null)
|
if (field == null)
|
||||||
throw new CompileException(Diagnostic.Error($"Struct '{target.Type}' does not have a field matching the name '{expression.Name.Ident}'").At(fileName, target).Build());
|
throw new CompileException(Diagnostic.Error($"Struct '{target.Type}' does not have a field matching the name '{expression.Name.Ident}'").At(fileName, target).Build());
|
||||||
|
|
||||||
return new TypedNodeExpressionMemberAccess(expression.Tokens, field.Type, target, expression.Name);
|
return new TypedNodeExpressionMemberAccess(expression.Tokens, field.Type, target, expression.Name);
|
||||||
|
}
|
||||||
|
case NubTypeEnumVariant enumVariantType:
|
||||||
|
{
|
||||||
|
if (!moduleGraph.TryResolveModule(enumVariantType.EnumType.Module, out var module))
|
||||||
|
throw new CompileException(Diagnostic.Error($"Module '{enumVariantType.EnumType.Module}' not found").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
|
if (!module.TryResolveType(enumVariantType.EnumType.Name, currentModule == enumVariantType.EnumType.Module, out var typeDef))
|
||||||
|
throw new CompileException(Diagnostic.Error($"Type '{enumVariantType.EnumType.Name}' not found in module '{enumVariantType.EnumType.Module}'").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
|
if (typeDef is not Module.TypeInfoEnum enumDef)
|
||||||
|
throw new CompileException(Diagnostic.Error($"Type '{enumVariantType.EnumType.Module}::{enumVariantType.EnumType.Name}' is not an enum").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
|
var variant = enumDef.Variants.FirstOrDefault(x => x.Name == enumVariantType.Variant);
|
||||||
|
if (variant == null)
|
||||||
|
throw new CompileException(Diagnostic.Error($"Type '{target.Type}' does not have a variant named '{enumVariantType.Variant}'").At(fileName, expression.Target).Build());
|
||||||
|
|
||||||
|
var field = variant.Fields.FirstOrDefault(x => x.Name == expression.Name.Ident);
|
||||||
|
if (field == null)
|
||||||
|
throw new CompileException(Diagnostic.Error($"Enum variant '{target.Type}' does not have a field matching the name '{expression.Name.Ident}'").At(fileName, target).Build());
|
||||||
|
|
||||||
|
return new TypedNodeExpressionMemberAccess(expression.Tokens, field.Type, target, expression.Name);
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
throw new CompileException(Diagnostic.Error($"{target.Type} has no member '{expression.Name.Ident}'").At(fileName, target).Build());
|
throw new CompileException(Diagnostic.Error($"{target.Type} has no member '{expression.Name.Ident}'").At(fileName, target).Build());
|
||||||
}
|
}
|
||||||
@@ -368,26 +409,17 @@ public class TypeChecker
|
|||||||
|
|
||||||
private TypedNodeExpressionStructLiteral CheckExpressionStructLiteral(NodeExpressionStructLiteral expression)
|
private TypedNodeExpressionStructLiteral CheckExpressionStructLiteral(NodeExpressionStructLiteral expression)
|
||||||
{
|
{
|
||||||
if (!moduleGraph.TryResolveModule(expression.Module.Ident, out var module))
|
var info = ResolveModuleStruct(ResolveModule(expression.Module), expression.Name);
|
||||||
throw new CompileException(Diagnostic.Error($"Module '{expression.Module.Ident}' not found").At(fileName, expression.Module).Build());
|
|
||||||
|
|
||||||
var includePrivate = expression.Module.Ident == moduleName;
|
|
||||||
|
|
||||||
if (!module.TryResolveType(expression.Name.Ident, includePrivate, out var typeDef))
|
|
||||||
throw new CompileException(Diagnostic.Error($"Struct '{expression.Module.Ident}::{expression.Name.Ident}' not found").At(fileName, expression.Name).Build());
|
|
||||||
|
|
||||||
if (typeDef is not Module.TypeInfoStruct structDef)
|
|
||||||
throw new CompileException(Diagnostic.Error($"Cannot create struct literal of non-struct type '{expression.Module.Ident}::{expression.Name.Ident}'").At(fileName, expression.Name).Build());
|
|
||||||
|
|
||||||
var initializers = new List<TypedNodeExpressionStructLiteral.Initializer>();
|
var initializers = new List<TypedNodeExpressionStructLiteral.Initializer>();
|
||||||
foreach (var initializer in expression.Initializers)
|
foreach (var initializer in expression.Initializers)
|
||||||
{
|
{
|
||||||
var field = structDef.Fields.FirstOrDefault(x => x.Name == initializer.Name.Ident);
|
var field = info.Fields.FirstOrDefault(x => x.Name == initializer.Name.Ident);
|
||||||
if (field == null)
|
if (field == null)
|
||||||
throw new CompileException(Diagnostic.Error($"Field '{initializer.Name.Ident}' does not exist on struct '{expression.Name.Ident}'").At(fileName, initializer.Name).Build());
|
throw new CompileException(Diagnostic.Error($"Field '{initializer.Name.Ident}' does not exist on struct '{expression.Module.Ident}::{expression.Name.Ident}'").At(fileName, initializer.Name).Build());
|
||||||
|
|
||||||
var value = CheckExpression(initializer.Value);
|
var value = CheckExpression(initializer.Value);
|
||||||
if (value.Type != field.Type)
|
if (!value.Type.IsAssignableTo(field.Type))
|
||||||
throw new CompileException(Diagnostic.Error($"Type of assignment ({value.Type}) does not match expected type of field '{field.Name}' ({field.Type})").At(fileName, initializer.Name).Build());
|
throw new CompileException(Diagnostic.Error($"Type of assignment ({value.Type}) does not match expected type of field '{field.Name}' ({field.Type})").At(fileName, initializer.Name).Build());
|
||||||
|
|
||||||
initializers.Add(new TypedNodeExpressionStructLiteral.Initializer(initializer.Tokens, initializer.Name, value));
|
initializers.Add(new TypedNodeExpressionStructLiteral.Initializer(initializer.Tokens, initializer.Name, value));
|
||||||
@@ -396,12 +428,37 @@ public class TypeChecker
|
|||||||
return new TypedNodeExpressionStructLiteral(expression.Tokens, NubTypeStruct.Get(expression.Module.Ident, expression.Name.Ident), initializers);
|
return new TypedNodeExpressionStructLiteral(expression.Tokens, NubTypeStruct.Get(expression.Module.Ident, expression.Name.Ident), initializers);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private TypedNodeExpressionEnumLiteral CheckExpressionEnumLiteral(NodeExpressionEnumLiteral expression)
|
||||||
|
{
|
||||||
|
var info = ResolveModuleEnum(ResolveModule(expression.Module), expression.EnumName);
|
||||||
|
|
||||||
|
var variant = info.Variants.FirstOrDefault(x => x.Name == expression.VariantName.Ident);
|
||||||
|
if (variant == null)
|
||||||
|
throw new CompileException(Diagnostic.Error($"Enum '{expression.Module.Ident}::{expression.EnumName.Ident}' does not have a variant '{expression.VariantName.Ident}'").At(fileName, expression.VariantName).Build());
|
||||||
|
|
||||||
|
var initializers = new List<TypedNodeExpressionEnumLiteral.Initializer>();
|
||||||
|
foreach (var initializer in expression.Initializers)
|
||||||
|
{
|
||||||
|
var field = variant.Fields.FirstOrDefault(x => x.Name == initializer.Name.Ident);
|
||||||
|
if (field == null)
|
||||||
|
throw new CompileException(Diagnostic.Error($"Field '{initializer.Name.Ident}' does not exist on enum variant '{expression.Module.Ident}::{expression.EnumName.Ident}.{expression.VariantName.Ident}'").At(fileName, initializer.Name).Build());
|
||||||
|
|
||||||
|
var value = CheckExpression(initializer.Value);
|
||||||
|
if (!value.Type.IsAssignableTo(field.Type))
|
||||||
|
throw new CompileException(Diagnostic.Error($"Type of assignment ({value.Type}) does not match expected type of field '{field.Name}' ({field.Type})").At(fileName, initializer.Name).Build());
|
||||||
|
|
||||||
|
initializers.Add(new TypedNodeExpressionEnumLiteral.Initializer(initializer.Tokens, initializer.Name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TypedNodeExpressionEnumLiteral(expression.Tokens, NubTypeEnumVariant.Get(NubTypeEnum.Get(expression.Module.Ident, expression.EnumName.Ident), expression.VariantName.Ident), initializers);
|
||||||
|
}
|
||||||
|
|
||||||
private NubType ResolveType(NodeType node)
|
private NubType ResolveType(NodeType node)
|
||||||
{
|
{
|
||||||
return node switch
|
return node switch
|
||||||
{
|
{
|
||||||
NodeTypeBool => NubTypeBool.Instance,
|
NodeTypeBool => NubTypeBool.Instance,
|
||||||
NodeTypeCustom type => ResolveCustomType(type),
|
NodeTypeNamed type => ResolveNamedType(type),
|
||||||
NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(ResolveType).ToList(), ResolveType(type.ReturnType)),
|
NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(ResolveType).ToList(), ResolveType(type.ReturnType)),
|
||||||
NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To)),
|
NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To)),
|
||||||
NodeTypeSInt type => NubTypeSInt.Get(type.Width),
|
NodeTypeSInt type => NubTypeSInt.Get(type.Width),
|
||||||
@@ -412,23 +469,127 @@ public class TypeChecker
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private NubType ResolveCustomType(NodeTypeCustom type)
|
private NubType ResolveNamedType(NodeTypeNamed type)
|
||||||
{
|
{
|
||||||
if (!moduleGraph.TryResolveModule(type.Module.Ident, out var module))
|
return type.Sections.Count switch
|
||||||
throw new CompileException(Diagnostic.Error($"Module '{type.Module.Ident}' not found").At(fileName, type.Module).Build());
|
|
||||||
|
|
||||||
var includePrivate = type.Module.Ident == moduleName;
|
|
||||||
|
|
||||||
if (!module.TryResolveType(type.Name.Ident, includePrivate, out var customType))
|
|
||||||
throw new CompileException(Diagnostic.Error($"Custom type '{type.Module.Ident}::{type.Name.Ident}' not found").At(fileName, type.Name).Build());
|
|
||||||
|
|
||||||
return customType switch
|
|
||||||
{
|
{
|
||||||
Module.TypeInfoStruct => NubTypeStruct.Get(type.Module.Ident, type.Name.Ident),
|
3 => ResolveThreePartType(type.Sections[0], type.Sections[1], type.Sections[2]),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(customType))
|
2 => ResolveTwoPartType(type.Sections[0], type.Sections[1]),
|
||||||
|
1 => ResolveOnePartType(type.Sections[0]),
|
||||||
|
_ => throw BasicError("Invalid type name", type)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private NubType ResolveThreePartType(TokenIdent first, TokenIdent second, TokenIdent third)
|
||||||
|
{
|
||||||
|
if (TryResolveEnumVariant(first.Ident, second.Ident, third.Ident, out var variantType))
|
||||||
|
return variantType;
|
||||||
|
|
||||||
|
throw BasicError($"Enum '{first.Ident}::{second.Ident}::{third.Ident}' does not have a variant named '{third.Ident}'", third);
|
||||||
|
}
|
||||||
|
|
||||||
|
private NubType ResolveTwoPartType(TokenIdent first, TokenIdent second)
|
||||||
|
{
|
||||||
|
if (TryResolveEnumVariant(currentModule, first.Ident, second.Ident, out var variantType))
|
||||||
|
return variantType;
|
||||||
|
|
||||||
|
var typeInfo = ResolveModuleTypeInfo(ResolveModule(first), second);
|
||||||
|
return typeInfo switch
|
||||||
|
{
|
||||||
|
Module.TypeInfoStruct => NubTypeStruct.Get(first.Ident, second.Ident),
|
||||||
|
Module.TypeInfoEnum => NubTypeEnum.Get(first.Ident, second.Ident),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private NubType ResolveOnePartType(TokenIdent name)
|
||||||
|
{
|
||||||
|
if (!moduleGraph.TryResolveModule(currentModule, out var module))
|
||||||
|
throw BasicError($"Module '{currentModule}' not found", name);
|
||||||
|
|
||||||
|
var typeInfo = ResolveModuleTypeInfo(module, name);
|
||||||
|
return typeInfo switch
|
||||||
|
{
|
||||||
|
Module.TypeInfoStruct => NubTypeStruct.Get(currentModule, name.Ident),
|
||||||
|
Module.TypeInfoEnum => NubTypeEnum.Get(currentModule, name.Ident),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Module ResolveModule(TokenIdent name)
|
||||||
|
{
|
||||||
|
if (!moduleGraph.TryResolveModule(name.Ident, out var module))
|
||||||
|
throw BasicError($"Module '{name.Ident}' not found", name);
|
||||||
|
|
||||||
|
return module;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Module.IdentifierInfo ResolveModuleIdentifier(Module module, TokenIdent name)
|
||||||
|
{
|
||||||
|
if (!module.TryResolveIdentifier(name.Ident, currentModule == module.Name, out var type))
|
||||||
|
throw BasicError($"Identifier '{module.Name}::{name.Ident}' not found", name);
|
||||||
|
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Module.TypeInfo ResolveModuleTypeInfo(Module module, TokenIdent name)
|
||||||
|
{
|
||||||
|
if (!module.TryResolveType(name.Ident, currentModule == module.Name, out var type))
|
||||||
|
throw BasicError($"Named type '{module.Name}::{name.Ident}' not found", name);
|
||||||
|
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Module.TypeInfoEnum ResolveModuleEnum(Module module, TokenIdent name)
|
||||||
|
{
|
||||||
|
var type = ResolveModuleTypeInfo(module, name);
|
||||||
|
if (type is not Module.TypeInfoEnum info)
|
||||||
|
throw BasicError($"'{module.Name}::{name.Ident}' is not an enum", name);
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Module.TypeInfoStruct ResolveModuleStruct(Module module, TokenIdent name)
|
||||||
|
{
|
||||||
|
var type = ResolveModuleTypeInfo(module, name);
|
||||||
|
if (type is not Module.TypeInfoStruct info)
|
||||||
|
throw BasicError($"'{module.Name}::{name.Ident}' is not a struct", name);
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryResolveEnumVariant(string moduleName, string enumName, string variantName, [NotNullWhen(true)] out NubType? result)
|
||||||
|
{
|
||||||
|
result = null;
|
||||||
|
|
||||||
|
if (!moduleGraph.TryResolveModule(moduleName, out var module))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!module.TryResolveType(enumName, true, out var type))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (type is not Module.TypeInfoEnum enumInfo)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == variantName);
|
||||||
|
|
||||||
|
if (variant == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
result = NubTypeEnumVariant.Get(NubTypeEnum.Get(moduleName, enumName), variantName);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompileException BasicError(string message, TokenIdent ident)
|
||||||
|
{
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class Scope
|
private sealed class Scope
|
||||||
{
|
{
|
||||||
private readonly Stack<Dictionary<string, NubType>> scopes = new();
|
private readonly Stack<Dictionary<string, NubType>> scopes = new();
|
||||||
@@ -539,10 +700,23 @@ public class TypedNodeStatementIf(List<Token> tokens, TypedNodeExpression condit
|
|||||||
public TypedNodeStatement? ElseBlock { get; } = elseBlock;
|
public TypedNodeStatement? ElseBlock { get; } = elseBlock;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class TypedNodeStatementWhile(List<Token> tokens, TypedNodeExpression condition, TypedNodeStatement block) : TypedNodeStatement(tokens)
|
public class TypedNodeStatementWhile(List<Token> tokens, TypedNodeExpression condition, TypedNodeStatement body) : TypedNodeStatement(tokens)
|
||||||
{
|
{
|
||||||
public TypedNodeExpression Condition { get; } = condition;
|
public TypedNodeExpression Condition { get; } = condition;
|
||||||
public TypedNodeStatement Block { get; } = block;
|
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 TokenIdent Type { get; } = type;
|
||||||
|
public TokenIdent VariableName { get; } = variableName;
|
||||||
|
public TypedNodeStatement Body { get; } = body;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public abstract class TypedNodeExpression(List<Token> tokens, NubType type) : TypedNode(tokens)
|
public abstract class TypedNodeExpression(List<Token> tokens, NubType type) : TypedNode(tokens)
|
||||||
@@ -576,6 +750,17 @@ public class TypedNodeExpressionStructLiteral(List<Token> tokens, NubType type,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class TypedNodeExpressionEnumLiteral(List<Token> tokens, NubType type, List<TypedNodeExpressionEnumLiteral.Initializer> initializers) : TypedNodeExpression(tokens, type)
|
||||||
|
{
|
||||||
|
public List<Initializer> Initializers { get; } = initializers;
|
||||||
|
|
||||||
|
public class Initializer(List<Token> tokens, TokenIdent name, TypedNodeExpression value) : Node(tokens)
|
||||||
|
{
|
||||||
|
public TokenIdent Name { get; } = name;
|
||||||
|
public TypedNodeExpression Value { get; } = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public class TypedNodeExpressionMemberAccess(List<Token> tokens, NubType type, TypedNodeExpression target, TokenIdent name) : TypedNodeExpression(tokens, type)
|
public class TypedNodeExpressionMemberAccess(List<Token> tokens, NubType type, TypedNodeExpression target, TokenIdent name) : TypedNodeExpression(tokens, type)
|
||||||
{
|
{
|
||||||
public TypedNodeExpression Target { get; } = target;
|
public TypedNodeExpression Target { get; } = target;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
set -e
|
||||||
|
|
||||||
pushd math
|
pushd math
|
||||||
dotnet run --project ../../compiler math.nub --type=lib
|
dotnet run --project ../../compiler math.nub --type=lib
|
||||||
pushd .build
|
pushd .build
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ module math
|
|||||||
struct vec2 { x: i32 y: i32 }
|
struct vec2 { x: i32 y: i32 }
|
||||||
struct vec3 { x: i32 y: i32 z: i32 }
|
struct vec3 { x: i32 y: i32 z: i32 }
|
||||||
struct color { r: i32 g: i32 b: i32 a: i32 }
|
struct color { r: i32 g: i32 b: i32 a: i32 }
|
||||||
struct example { a: math::vec2 b: math::vec3 c: math::color }
|
struct example { a: vec2 b: vec3 c: color }
|
||||||
|
|
||||||
export enum message {
|
export enum message {
|
||||||
quit
|
quit
|
||||||
@@ -15,6 +15,16 @@ export enum message {
|
|||||||
|
|
||||||
export func add(a: i32 b: i32): i32
|
export func add(a: i32 b: i32): i32
|
||||||
{
|
{
|
||||||
|
let message: message = enum math::message::move { x = 1 y = 1 }
|
||||||
|
|
||||||
|
match message {
|
||||||
|
quit q {}
|
||||||
|
move m {
|
||||||
|
m.x = 23
|
||||||
|
m.y = 23
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return math::add_internal(a b)
|
return math::add_internal(a b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user