Compare commits
58 Commits
0a5b39b217
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa5a494d39 | ||
|
|
bc65c3f4fd | ||
|
|
bdeb2c4d73 | ||
|
|
48760dcdda | ||
|
|
63d0eb660b | ||
|
|
918d25f8c8 | ||
|
|
6e631ba1ba | ||
|
|
832184053f | ||
|
|
2ab20652f8 | ||
|
|
6507624e90 | ||
|
|
83255980d7 | ||
|
|
1a1dc1389d | ||
|
|
4210ad878b | ||
|
|
32042d0769 | ||
|
|
dd44e3edc4 | ||
|
|
24d41d3dcb | ||
|
|
c9bf212aa2 | ||
|
|
0e099d0baf | ||
|
|
0be4e35628 | ||
|
|
7dd635fa91 | ||
|
|
693b119781 | ||
|
|
2b7eb56895 | ||
|
|
5f4a4172bf | ||
|
|
9da370e387 | ||
|
|
faf506f409 | ||
|
|
16d27c76ab | ||
|
|
270be1f740 | ||
|
|
da2fa81c39 | ||
|
|
677c7dea9e | ||
|
|
6ba05d00d7 | ||
|
|
d58e006be4 | ||
|
|
84627dde45 | ||
|
|
e7aad861d3 | ||
|
|
ecb628c4c2 | ||
|
|
e5227f7a99 | ||
|
|
73ecbf8e9b | ||
|
|
e512650440 | ||
|
|
272ea33616 | ||
|
|
b7dc77cb1c | ||
|
|
3323d760e8 | ||
|
|
aa5bf0b568 | ||
|
|
660166221c | ||
|
|
49734544e6 | ||
|
|
cb4aeb9c01 | ||
|
|
d771396bd4 | ||
|
|
7b1e202424 | ||
|
|
282dd0502a | ||
|
|
3ebaa67b6d | ||
|
|
35867ffa28 | ||
|
|
76efc84984 | ||
|
|
583c01201f | ||
|
|
1511d5d2b8 | ||
|
|
caa3b378b3 | ||
|
|
cbe27c0ae8 | ||
|
|
4d0f7c715f | ||
|
|
c342b2e102 | ||
|
|
ee485e4119 | ||
|
|
21a095f691 |
File diff suppressed because it is too large
Load Diff
@@ -19,119 +19,40 @@ public class ModuleGraph
|
||||
return modules.Values.ToList();
|
||||
}
|
||||
|
||||
public bool TryResolveIdentifier(string moduleName, string identifierName, bool searchPrivate, [NotNullWhen(true)] out Module.IdentifierInfo? info)
|
||||
{
|
||||
if (!TryResolveModule(moduleName, out var module))
|
||||
{
|
||||
info = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!module.TryResolveIdentifier(identifierName, searchPrivate, out info))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryResolveType(string moduleName, string typeName, bool searchPrivate, [NotNullWhen(true)] out Module.TypeInfo? info)
|
||||
{
|
||||
if (!TryResolveModule(moduleName, out var module))
|
||||
{
|
||||
info = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!module.TryResolveType(typeName, searchPrivate, out info))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryResolveModule(string moduleName, [NotNullWhen(true)] out Module? module)
|
||||
{
|
||||
module = modules.GetValueOrDefault(moduleName);
|
||||
return module != null;
|
||||
}
|
||||
|
||||
public Manifest CreateManifest()
|
||||
{
|
||||
return new Manifest(1, GetModules().Select(x => x.CreateManifestModule()).ToList());
|
||||
}
|
||||
|
||||
public class Module(string name)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
private readonly Dictionary<string, CustomTypeInfo> customTypes = new();
|
||||
private readonly Dictionary<string, IdentifierInfo> identifierTypes = new();
|
||||
|
||||
public IReadOnlyList<NubType> GetCustomTypes()
|
||||
{
|
||||
return customTypes.Values.Select(x => x.Type).ToList();
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<string, NubType> GetIdentifierTypes()
|
||||
{
|
||||
return identifierTypes.ToDictionary(x => x.Key, x => x.Value.Type);
|
||||
}
|
||||
|
||||
public bool TryResolveCustomType(string name, bool searchPrivate, [NotNullWhen(true)] out NubType? customType)
|
||||
{
|
||||
var info = customTypes.GetValueOrDefault(name);
|
||||
if (info == null)
|
||||
{
|
||||
customType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (info.Exported || searchPrivate)
|
||||
{
|
||||
customType = info.Type;
|
||||
return true;
|
||||
}
|
||||
|
||||
customType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveIdentifierType(string name, bool searchPrivate, [NotNullWhen(true)] out NubType? identifierType)
|
||||
{
|
||||
var info = identifierTypes.GetValueOrDefault(name);
|
||||
if (info == null)
|
||||
{
|
||||
identifierType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (info.Exported || searchPrivate)
|
||||
{
|
||||
identifierType = info.Type;
|
||||
return true;
|
||||
}
|
||||
|
||||
identifierType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void AddCustomType(string name, CustomTypeInfo info)
|
||||
{
|
||||
customTypes.Add(name, info);
|
||||
}
|
||||
|
||||
public void AddIdentifier(string name, IdentifierInfo info)
|
||||
{
|
||||
identifierTypes.Add(name, info);
|
||||
}
|
||||
|
||||
public ManifestModule CreateManifestModule()
|
||||
{
|
||||
var manifestCustomTypes = customTypes.ToDictionary(x => x.Key, x => x.Value.CreateManifestCustomTypeInfo());
|
||||
var manifestIdentifiers = identifierTypes.ToDictionary(x => x.Key, x => x.Value.CreateManifestIdentifierInfo());
|
||||
return new ManifestModule(Name, manifestCustomTypes, manifestIdentifiers);
|
||||
}
|
||||
|
||||
public enum Source
|
||||
{
|
||||
Ast,
|
||||
Lib,
|
||||
}
|
||||
|
||||
public class CustomTypeInfo(NubType type, bool exported, Source source)
|
||||
{
|
||||
public NubType Type { get; } = type;
|
||||
public bool Exported { get; } = exported;
|
||||
public Source Source { get; } = source;
|
||||
|
||||
public ManifestCustomTypeInfo CreateManifestCustomTypeInfo()
|
||||
{
|
||||
return new ManifestCustomTypeInfo(TypeEncoder.Encode(Type), Exported);
|
||||
}
|
||||
}
|
||||
|
||||
public class IdentifierInfo(NubType type, bool exported, Source source)
|
||||
{
|
||||
public NubType Type { get; } = type;
|
||||
public bool Exported { get; } = exported;
|
||||
public Source Source { get; } = source;
|
||||
|
||||
public ManifestIdentifierInfo CreateManifestIdentifierInfo()
|
||||
{
|
||||
return new ManifestIdentifierInfo(TypeEncoder.Encode(Type), Exported);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Builder
|
||||
{
|
||||
private readonly List<Ast> asts = [];
|
||||
@@ -153,90 +74,121 @@ public class ModuleGraph
|
||||
|
||||
var modules = new Dictionary<string, Module>();
|
||||
|
||||
// First pass: Register libraries
|
||||
foreach (var manifest in manifests)
|
||||
{
|
||||
foreach (var manifestModule in manifest.Modules)
|
||||
foreach (var (moduleName, manifestModule) in manifest.Modules)
|
||||
{
|
||||
if (!modules.TryGetValue(manifestModule.Name, out var module))
|
||||
var module = GetOrCreateModule(moduleName);
|
||||
|
||||
foreach (var (name, type) in manifestModule.Types)
|
||||
{
|
||||
module = new Module(manifestModule.Name);
|
||||
modules.Add(manifestModule.Name, module);
|
||||
switch (type)
|
||||
{
|
||||
case Manifest.Module.TypeInfoStruct s:
|
||||
{
|
||||
var info = new Module.TypeInfoStruct(Module.DefinitionSource.Imported, s.Exported, s.Packed);
|
||||
var fields = s.Fields.Select(x => new Module.TypeInfoStruct.Field(x.Name, x.Type)).ToList();
|
||||
info.SetFields(fields);
|
||||
module.AddType(name, info);
|
||||
break;
|
||||
}
|
||||
case Manifest.Module.TypeInfoEnum e:
|
||||
{
|
||||
var info = new Module.TypeInfoEnum(Module.DefinitionSource.Imported, e.Exported);
|
||||
var variants = e.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name, v.Type)).ToList();
|
||||
info.SetVariants(variants);
|
||||
module.AddType(name, info);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(type));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var customType in manifestModule.CustomTypes)
|
||||
foreach (var (name, identifier) in manifestModule.Identifiers)
|
||||
{
|
||||
var decoded = TypeDecoder.Decode(customType.Value.EncodedType);
|
||||
module.AddCustomType(customType.Key, new Module.CustomTypeInfo(decoded, customType.Value.Exported, Module.Source.Lib));
|
||||
}
|
||||
|
||||
foreach (var identifier in manifestModule.Identifiers)
|
||||
{
|
||||
var decoded = TypeDecoder.Decode(identifier.Value.EncodedType);
|
||||
module.AddIdentifier(identifier.Key, new Module.IdentifierInfo(decoded, identifier.Value.Exported, Module.Source.Lib));
|
||||
module.AddIdentifier(name, new Module.IdentifierInfo(Module.DefinitionSource.Imported, identifier.Exported, identifier.Extern, identifier.Type, identifier.MangledName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var astModuleCache = new Dictionary<Ast, Module>();
|
||||
|
||||
// Second pass: Register modules from ast
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
if (!modules.ContainsKey(ast.ModuleName.Ident))
|
||||
{
|
||||
var module = new Module(ast.ModuleName.Ident);
|
||||
modules.Add(ast.ModuleName.Ident, module);
|
||||
astModuleCache[ast] = module;
|
||||
}
|
||||
}
|
||||
|
||||
// Third pass: Register struct types without fields
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
var module = astModuleCache[ast];
|
||||
var module = GetOrCreateModule(ast.ModuleName.Ident);
|
||||
|
||||
foreach (var structDef in ast.Definitions.OfType<NodeDefinitionStruct>())
|
||||
{
|
||||
var type = new NubTypeStruct(module.Name, structDef.Name.Ident, structDef.Packed);
|
||||
var info = new Module.CustomTypeInfo(type, structDef.Exported, Module.Source.Ast);
|
||||
module.AddCustomType(structDef.Name.Ident, info);
|
||||
module.AddType(structDef.Name.Ident, new Module.TypeInfoStruct(Module.DefinitionSource.Internal, structDef.Exported, structDef.Packed));
|
||||
}
|
||||
|
||||
foreach (var enumDef in ast.Definitions.OfType<NodeDefinitionEnum>())
|
||||
{
|
||||
module.AddType(enumDef.Name.Ident, new Module.TypeInfoEnum(Module.DefinitionSource.Internal, enumDef.Exported));
|
||||
}
|
||||
}
|
||||
|
||||
// Fourth pass: Resolve struct fields
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
var module = astModuleCache[ast];
|
||||
var module = GetOrCreateModule(ast.ModuleName.Ident);
|
||||
|
||||
foreach (var structDef in ast.Definitions.OfType<NodeDefinitionStruct>())
|
||||
{
|
||||
if (!module.TryResolveCustomType(structDef.Name.Ident, true, out var customType))
|
||||
throw new UnreachableException($"{nameof(customType)} should always be registered");
|
||||
if (!module.TryResolveType(structDef.Name.Ident, true, out var typeInfo))
|
||||
throw new UnreachableException($"{nameof(typeInfo)} should always be registered");
|
||||
|
||||
var fields = structDef.Fields.Select(f => new NubTypeStruct.Field(f.Name.Ident, ResolveType(f.Type, module.Name))).ToList();
|
||||
((NubTypeStruct)customType).ResolveFields(fields);
|
||||
if (typeInfo is Module.TypeInfoStruct structType)
|
||||
{
|
||||
var fields = structDef.Fields.Select(f => new Module.TypeInfoStruct.Field(f.Name.Ident, ResolveType(f.Type, module.Name))).ToList();
|
||||
structType.SetFields(fields);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var enumDef in ast.Definitions.OfType<NodeDefinitionEnum>())
|
||||
{
|
||||
if (!module.TryResolveType(enumDef.Name.Ident, true, out var typeInfo))
|
||||
throw new UnreachableException($"{nameof(typeInfo)} should always be registered");
|
||||
|
||||
if (typeInfo is Module.TypeInfoEnum enumType)
|
||||
{
|
||||
var variants = enumDef.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name.Ident, v.Type == null ? null : ResolveType(v.Type, module.Name))).ToList();
|
||||
enumType.SetVariants(variants);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fifth pass: Register identifiers
|
||||
foreach (var ast in asts)
|
||||
{
|
||||
var module = astModuleCache[ast];
|
||||
var module = GetOrCreateModule(ast.ModuleName.Ident);
|
||||
|
||||
foreach (var funcDef in ast.Definitions.OfType<NodeDefinitionFunc>())
|
||||
{
|
||||
var parameters = funcDef.Parameters.Select(x => ResolveType(x.Type, module.Name)).ToList();
|
||||
var returnType = ResolveType(funcDef.ReturnType, module.Name);
|
||||
var returnType = funcDef.ReturnType == null ? NubTypeVoid.Instance : ResolveType(funcDef.ReturnType, module.Name);
|
||||
var funcType = NubTypeFunc.Get(parameters, returnType);
|
||||
var info = new Module.IdentifierInfo(funcType, funcDef.Exported, Module.Source.Ast);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, funcDef.Exported, false, funcType, NameMangler.Mangle(module.Name, funcDef.Name.Ident, funcType));
|
||||
module.AddIdentifier(funcDef.Name.Ident, info);
|
||||
}
|
||||
|
||||
foreach (var funcDef in ast.Definitions.OfType<NodeDefinitionExternFunc>())
|
||||
{
|
||||
var parameters = funcDef.Parameters.Select(x => ResolveType(x.Type, module.Name)).ToList();
|
||||
var returnType = funcDef.ReturnType == null ? NubTypeVoid.Instance : ResolveType(funcDef.ReturnType, module.Name);
|
||||
var funcType = NubTypeFunc.Get(parameters, returnType);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, funcDef.Exported, true, funcType, funcDef.Name.Ident);
|
||||
module.AddIdentifier(funcDef.Name.Ident, info);
|
||||
}
|
||||
|
||||
foreach (var globalVariable in ast.Definitions.OfType<NodeDefinitionGlobalVariable>())
|
||||
{
|
||||
var type = ResolveType(globalVariable.Type, module.Name);
|
||||
var info = new Module.IdentifierInfo(type, globalVariable.Exported, Module.Source.Ast);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, globalVariable.Exported, false, type, NameMangler.Mangle(module.Name, globalVariable.Name.Ident, type));
|
||||
module.AddIdentifier(globalVariable.Name.Ident, info);
|
||||
}
|
||||
|
||||
foreach (var globalVariable in ast.Definitions.OfType<NodeDefinitionExternGlobalVariable>())
|
||||
{
|
||||
var type = ResolveType(globalVariable.Type, module.Name);
|
||||
var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, globalVariable.Exported, true, type, NameMangler.Mangle(module.Name, globalVariable.Name.Ident, type));
|
||||
module.AddIdentifier(globalVariable.Name.Ident, info);
|
||||
}
|
||||
}
|
||||
@@ -251,35 +203,244 @@ public class ModuleGraph
|
||||
return node switch
|
||||
{
|
||||
NodeTypeBool => NubTypeBool.Instance,
|
||||
NodeTypeCustom type => ResolveCustomType(type, currentModule),
|
||||
NodeTypeNamed type => ResolveNamedType(type, currentModule),
|
||||
NodeTypeAnonymousStruct type => NubTypeAnonymousStruct.Get(type.Fields.Select(x => new NubTypeAnonymousStruct.Field(x.Name.Ident, ResolveType(x.Type, currentModule))).ToList()),
|
||||
NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(x => ResolveType(x, currentModule)).ToList(), ResolveType(type.ReturnType, currentModule)),
|
||||
NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To, currentModule)),
|
||||
NodeTypeSInt type => NubTypeSInt.Get(type.Width),
|
||||
NodeTypeUInt type => NubTypeUInt.Get(type.Width),
|
||||
NodeTypeString => NubTypeString.Instance,
|
||||
NodeTypeChar => NubTypeChar.Instance,
|
||||
NodeTypeVoid => NubTypeVoid.Instance,
|
||||
NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType, currentModule)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
}
|
||||
|
||||
NubType ResolveCustomType(NodeTypeCustom type, string currentModule)
|
||||
NubType ResolveNamedType(NodeTypeNamed type, string currentModule)
|
||||
{
|
||||
var module = modules.GetValueOrDefault(type.Module.Ident);
|
||||
if (module == null)
|
||||
throw new CompileException(Diagnostic.Error($"Unknown module: {type.Module.Ident}").Build());
|
||||
return type.Sections.Count switch
|
||||
{
|
||||
3 => ResolveThreePartType(type.Sections[0], type.Sections[1], type.Sections[2], currentModule),
|
||||
2 => ResolveTwoPartType(type.Sections[0], type.Sections[1], currentModule),
|
||||
1 => ResolveOnePartType(type.Sections[0], currentModule),
|
||||
_ => throw BasicError("Invalid type name")
|
||||
};
|
||||
}
|
||||
|
||||
var includePrivate = currentModule == type.Module.Ident;
|
||||
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 (!module.TryResolveCustomType(type.Name.Ident, includePrivate, out var customType))
|
||||
throw new CompileException(Diagnostic.Error($"Unknown custom type: {type.Module.Ident}::{type.Name.Ident}").Build());
|
||||
if (typeInfo is not Module.TypeInfoEnum enumInfo)
|
||||
throw BasicError($"'{module.Name}::{second.Ident}' is not an enum");
|
||||
|
||||
return customType;
|
||||
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == third.Ident);
|
||||
if (variant == null)
|
||||
throw BasicError($"Enum '{module.Name}::{second.Ident}' does not have a variant named '{third.Ident}'");
|
||||
|
||||
return NubTypeEnumVariant.Get(NubTypeEnum.Get(module.Name, second.Ident), third.Ident);
|
||||
}
|
||||
|
||||
NubType ResolveTwoPartType(TokenIdent first, TokenIdent second, string currentModule)
|
||||
{
|
||||
if (TryResolveEnumVariant(currentModule, first.Ident, second.Ident, out var variant))
|
||||
return variant;
|
||||
|
||||
var module = ResolveModule(first);
|
||||
if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo))
|
||||
throw BasicError($"Named type '{module.Name}::{second.Ident}' not found");
|
||||
|
||||
return typeInfo switch
|
||||
{
|
||||
Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, second.Ident),
|
||||
Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, second.Ident),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||
};
|
||||
}
|
||||
|
||||
NubType ResolveOnePartType(TokenIdent name, string currentModule)
|
||||
{
|
||||
if (!modules.TryGetValue(currentModule, out var module))
|
||||
throw BasicError($"Module '{currentModule}' not found");
|
||||
|
||||
if (!module.TryResolveType(name.Ident, true, out var typeInfo))
|
||||
throw BasicError($"Named type '{module.Name}::{name.Ident}' not found");
|
||||
|
||||
return typeInfo switch
|
||||
{
|
||||
Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, name.Ident),
|
||||
Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, name.Ident),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||
};
|
||||
}
|
||||
|
||||
Module ResolveModule(TokenIdent name)
|
||||
{
|
||||
if (!modules.TryGetValue(name.Ident, out var module))
|
||||
throw BasicError($"Module '{name.Ident}' not found");
|
||||
|
||||
return module;
|
||||
}
|
||||
|
||||
bool TryResolveEnumVariant(string moduleName, string enumName, string variantName, [NotNullWhen(true)] out NubType? result)
|
||||
{
|
||||
result = null;
|
||||
|
||||
if (!modules.TryGetValue(moduleName, out var module))
|
||||
return false;
|
||||
|
||||
if (!module.TryResolveType(enumName, true, out var typeInfo))
|
||||
return false;
|
||||
|
||||
if (typeInfo is not Module.TypeInfoEnum enumInfo)
|
||||
return false;
|
||||
|
||||
var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == variantName);
|
||||
if (variant == null)
|
||||
return false;
|
||||
|
||||
result = NubTypeEnumVariant.Get(
|
||||
NubTypeEnum.Get(moduleName, enumName),
|
||||
variantName);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Exception BasicError(string message)
|
||||
{
|
||||
return new CompileException(Diagnostic.Error(message).Build());
|
||||
}
|
||||
|
||||
Module GetOrCreateModule(string name)
|
||||
{
|
||||
if (!modules.TryGetValue(name, out var module))
|
||||
{
|
||||
module = new Module(name);
|
||||
modules.Add(name, module);
|
||||
}
|
||||
|
||||
return module;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Manifest(int Version, IReadOnlyList<ManifestModule> Modules);
|
||||
public record ManifestModule(string Name, Dictionary<string, ManifestCustomTypeInfo> CustomTypes, Dictionary<string, ManifestIdentifierInfo> Identifiers);
|
||||
public record ManifestCustomTypeInfo(string EncodedType, bool Exported);
|
||||
public record ManifestIdentifierInfo(string EncodedType, bool Exported);
|
||||
public class Module(string name)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
|
||||
private Dictionary<string, TypeInfo> types = new();
|
||||
private Dictionary<string, IdentifierInfo> identifiers = new();
|
||||
|
||||
public IReadOnlyDictionary<string, TypeInfo> GetTypes() => types;
|
||||
public IReadOnlyDictionary<string, IdentifierInfo> GetIdentifiers() => identifiers;
|
||||
|
||||
public bool TryResolveType(string name, bool searchPrivate, [NotNullWhen(true)] out TypeInfo? customType)
|
||||
{
|
||||
var info = types.GetValueOrDefault(name);
|
||||
if (info == null)
|
||||
{
|
||||
customType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (searchPrivate || info.Source == DefinitionSource.Internal)
|
||||
{
|
||||
customType = info;
|
||||
return true;
|
||||
}
|
||||
|
||||
customType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveIdentifier(string name, bool searchPrivate, [NotNullWhen(true)] out IdentifierInfo? identifierType)
|
||||
{
|
||||
var info = identifiers.GetValueOrDefault(name);
|
||||
if (info == null)
|
||||
{
|
||||
identifierType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (searchPrivate || info.Source == DefinitionSource.Internal)
|
||||
{
|
||||
identifierType = info;
|
||||
return true;
|
||||
}
|
||||
|
||||
identifierType = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void AddType(string name, TypeInfo info)
|
||||
{
|
||||
types.Add(name, info);
|
||||
}
|
||||
|
||||
public void AddIdentifier(string name, IdentifierInfo info)
|
||||
{
|
||||
identifiers.Add(name, info);
|
||||
}
|
||||
|
||||
public enum DefinitionSource
|
||||
{
|
||||
Internal,
|
||||
Imported,
|
||||
}
|
||||
|
||||
public class IdentifierInfo(DefinitionSource source, bool exported, bool @extern, NubType type, string mangledName)
|
||||
{
|
||||
public DefinitionSource Source { get; } = source;
|
||||
public bool Exported { get; } = exported;
|
||||
public bool Extern { get; } = @extern;
|
||||
public NubType Type { get; } = type;
|
||||
public string MangledName { get; } = mangledName;
|
||||
}
|
||||
|
||||
public abstract class TypeInfo(DefinitionSource source, bool exported)
|
||||
{
|
||||
public DefinitionSource Source { get; } = source;
|
||||
public bool Exported { get; } = exported;
|
||||
}
|
||||
|
||||
public class TypeInfoStruct(DefinitionSource source, bool exported, bool packed) : TypeInfo(source, exported)
|
||||
{
|
||||
private IReadOnlyList<Field>? fields;
|
||||
|
||||
public bool Packed { get; } = packed;
|
||||
public IReadOnlyList<Field> Fields => fields ?? throw new InvalidOperationException("Fields has not been set yet");
|
||||
|
||||
public void SetFields(IReadOnlyList<Field> fields)
|
||||
{
|
||||
this.fields = fields;
|
||||
}
|
||||
|
||||
public class Field(string name, NubType type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType Type { get; } = type;
|
||||
}
|
||||
}
|
||||
|
||||
public class TypeInfoEnum(DefinitionSource source, bool exported) : TypeInfo(source, exported)
|
||||
{
|
||||
private IReadOnlyList<Variant>? variants;
|
||||
|
||||
public IReadOnlyList<Variant> Variants => variants ?? throw new InvalidOperationException("Fields has not been set yet");
|
||||
|
||||
public void SetVariants(IReadOnlyList<Variant> variants)
|
||||
{
|
||||
this.variants = variants;
|
||||
}
|
||||
|
||||
public class Variant(string name, NubType? type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType? Type { get; } = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
@@ -32,7 +33,7 @@ public class NubLib
|
||||
fileStream.CopyTo(entryStream);
|
||||
}
|
||||
|
||||
public static NublibLoadResult Unpack(string nublibPath)
|
||||
public static NubLibLoadResult Unpack(string nublibPath)
|
||||
{
|
||||
using var fs = new FileStream(nublibPath, FileMode.Open, FileAccess.Read);
|
||||
using var zip = new ZipArchive(fs, ZipArchiveMode.Read);
|
||||
@@ -55,8 +56,55 @@ public class NubLib
|
||||
entryStream.CopyTo(tempFile);
|
||||
}
|
||||
|
||||
return new NublibLoadResult(manifest, tempArchivePath);
|
||||
return new NubLibLoadResult(manifest, tempArchivePath);
|
||||
}
|
||||
|
||||
public record NublibLoadResult(Manifest Manifest, string ArchivePath);
|
||||
public record NubLibLoadResult(Manifest Manifest, string ArchivePath);
|
||||
}
|
||||
|
||||
public record Manifest(Dictionary<string, Manifest.Module> Modules)
|
||||
{
|
||||
public static Manifest Create(ModuleGraph moduleGraph)
|
||||
{
|
||||
var modules = new Dictionary<string, Module>();
|
||||
|
||||
foreach (var module in moduleGraph.GetModules())
|
||||
{
|
||||
var types = module.GetTypes().ToDictionary(x => x.Key, x => ConvertType(x.Value));
|
||||
var identifiers = module.GetIdentifiers().ToDictionary(x => x.Key, x => new Module.IdentifierInfo(x.Value.Type, x.Value.Exported, x.Value.Extern, x.Value.MangledName));
|
||||
modules[module.Name] = new Module(types, identifiers);
|
||||
}
|
||||
|
||||
return new Manifest(modules);
|
||||
|
||||
static Module.TypeInfo ConvertType(Compiler.Module.TypeInfo typeInfo)
|
||||
{
|
||||
return typeInfo switch
|
||||
{
|
||||
Compiler.Module.TypeInfoStruct s => new Module.TypeInfoStruct(s.Exported, s.Packed, s.Fields.Select(x => new Module.TypeInfoStruct.Field(x.Name, x.Type)).ToList()),
|
||||
Compiler.Module.TypeInfoEnum e => new Module.TypeInfoEnum(e.Exported, e.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name, v.Type)).ToList()),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(typeInfo))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record Module(Dictionary<string, Module.TypeInfo> Types, Dictionary<string, Module.IdentifierInfo> Identifiers)
|
||||
{
|
||||
public record IdentifierInfo(NubType Type, bool Exported, bool Extern, string MangledName);
|
||||
|
||||
[JsonDerivedType(typeof(TypeInfoStruct), "struct")]
|
||||
[JsonDerivedType(typeof(TypeInfoEnum), "enum")]
|
||||
public abstract record TypeInfo(bool Exported);
|
||||
|
||||
public record TypeInfoStruct(bool Exported, bool Packed, IReadOnlyList<TypeInfoStruct.Field> Fields) : TypeInfo(Exported)
|
||||
{
|
||||
public record Field(string Name, NubType Type);
|
||||
}
|
||||
|
||||
public record TypeInfoEnum(bool Exported, IReadOnlyList<TypeInfoEnum.Variant> Variants) : TypeInfo(Exported)
|
||||
{
|
||||
public record Variant(string Name, NubType? Type);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,28 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Compiler;
|
||||
|
||||
[JsonConverter(typeof(NubTypeJsonConverter))]
|
||||
public abstract class NubType
|
||||
{
|
||||
public abstract override string ToString();
|
||||
|
||||
[Obsolete("Use IsAssignableTo instead of ==", error: true)]
|
||||
public static bool operator ==(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo");
|
||||
|
||||
[Obsolete("Use IsAssignableTo instead of ==", error: true)]
|
||||
public static bool operator !=(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo");
|
||||
|
||||
public bool IsAssignableTo(NubType target)
|
||||
{
|
||||
return (this, target) switch
|
||||
{
|
||||
(NubTypeEnumVariant variant, NubTypeEnum targetEnum) => ReferenceEquals(variant.EnumType, targetEnum),
|
||||
_ => ReferenceEquals(this, target),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class NubTypeVoid : NubType
|
||||
@@ -84,38 +102,119 @@ 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
|
||||
{
|
||||
public string Name { get; }
|
||||
public string Module { get; }
|
||||
public bool Packed { get; }
|
||||
private static readonly Dictionary<(string Module, string Name), NubTypeStruct> Cache = new();
|
||||
|
||||
private IReadOnlyList<Field>? _resolvedFields;
|
||||
public static NubTypeStruct Get(string module, string name)
|
||||
{
|
||||
if (!Cache.TryGetValue((module, name), out var structType))
|
||||
Cache[(module, name)] = structType = new NubTypeStruct(module, name);
|
||||
|
||||
public IReadOnlyList<Field> Fields => _resolvedFields ?? throw new InvalidOperationException();
|
||||
return structType;
|
||||
}
|
||||
|
||||
public NubTypeStruct(string module, string name, bool packed)
|
||||
private NubTypeStruct(string module, string name)
|
||||
{
|
||||
Module = module;
|
||||
Name = name;
|
||||
Packed = packed;
|
||||
}
|
||||
|
||||
public void ResolveFields(IReadOnlyList<Field> fields)
|
||||
public string Module { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public override string ToString() => $"{Module}::{Name}";
|
||||
}
|
||||
|
||||
public class NubTypeAnonymousStruct : NubType
|
||||
{
|
||||
private static readonly Dictionary<Signature, NubTypeAnonymousStruct> Cache = new();
|
||||
|
||||
public static NubTypeAnonymousStruct Get(List<Field> fields)
|
||||
{
|
||||
if (_resolvedFields != null)
|
||||
throw new InvalidOperationException($"{Name} already resolved");
|
||||
var sig = new Signature(fields);
|
||||
|
||||
_resolvedFields = fields;
|
||||
if (!Cache.TryGetValue(sig, out var func))
|
||||
Cache[sig] = func = new NubTypeAnonymousStruct(fields);
|
||||
|
||||
return func;
|
||||
}
|
||||
|
||||
public override string ToString() => _resolvedFields == null ? $"struct {Module}::{Name} <unresolved>" : $"struct {Module}::{Name} {{ {string.Join(' ', Fields.Select(f => $"{f.Name}: {f.Type}"))} }}";
|
||||
private NubTypeAnonymousStruct(IReadOnlyList<Field> fields)
|
||||
{
|
||||
Fields = fields;
|
||||
}
|
||||
|
||||
public IReadOnlyList<Field> Fields { get; }
|
||||
|
||||
public override string ToString() => $"{{ {string.Join(", ", Fields.Select(x => $"{x.Name}: {x.Type}"))} }}";
|
||||
|
||||
public class Field(string name, NubType type)
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
public NubType Type { get; } = type;
|
||||
}
|
||||
|
||||
private record Signature(IReadOnlyList<Field> Fields);
|
||||
}
|
||||
|
||||
public class NubTypeEnum : NubType
|
||||
{
|
||||
private static readonly Dictionary<(string Module, string Name), NubTypeEnum> Cache = new();
|
||||
|
||||
public static NubTypeEnum Get(string module, string name)
|
||||
{
|
||||
if (!Cache.TryGetValue((module, name), out var enumType))
|
||||
Cache[(module, name)] = enumType = new NubTypeEnum(module, name);
|
||||
|
||||
return enumType;
|
||||
}
|
||||
|
||||
private NubTypeEnum(string module, string name)
|
||||
{
|
||||
Module = module;
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Module { get; }
|
||||
public string Name { get; }
|
||||
|
||||
public override string ToString() => $"{Module}::{Name}";
|
||||
}
|
||||
|
||||
public class NubTypeEnumVariant : NubType
|
||||
{
|
||||
private static readonly Dictionary<(NubTypeEnum EnumType, string Variant), NubTypeEnumVariant> Cache = new();
|
||||
|
||||
public static NubTypeEnumVariant Get(NubTypeEnum enumType, string variant)
|
||||
{
|
||||
if (!Cache.TryGetValue((enumType, variant), out var variantType))
|
||||
Cache[(enumType, variant)] = variantType = new NubTypeEnumVariant(enumType, variant);
|
||||
|
||||
return variantType;
|
||||
}
|
||||
|
||||
private NubTypeEnumVariant(NubTypeEnum enumType, string variant)
|
||||
{
|
||||
EnumType = enumType;
|
||||
Variant = variant;
|
||||
}
|
||||
|
||||
public NubTypeEnum EnumType { get; }
|
||||
public string Variant { get; }
|
||||
|
||||
public override string ToString() => $"{EnumType}.{Variant}";
|
||||
}
|
||||
|
||||
public class NubTypePointer : NubType
|
||||
@@ -157,8 +256,6 @@ public class NubTypeFunc : NubType
|
||||
public IReadOnlyList<NubType> Parameters { get; }
|
||||
public NubType ReturnType { get; }
|
||||
|
||||
public string MangledName(string name, string module) => SymbolNameGen.Exported(name, module, this);
|
||||
|
||||
private NubTypeFunc(List<NubType> parameters, NubType returnType)
|
||||
{
|
||||
Parameters = parameters;
|
||||
@@ -167,19 +264,50 @@ public class NubTypeFunc : NubType
|
||||
|
||||
public override string ToString() => $"func({string.Join(' ', Parameters)}): {ReturnType}";
|
||||
|
||||
private readonly record struct Signature(IReadOnlyList<NubType> Parameters, NubType ReturnType);
|
||||
private record Signature(IReadOnlyList<NubType> Parameters, NubType ReturnType);
|
||||
}
|
||||
|
||||
static class TypeEncoder
|
||||
public class NubTypeArray : NubType
|
||||
{
|
||||
private static readonly Dictionary<NubType, NubTypeArray> Cache = new();
|
||||
|
||||
public static NubTypeArray Get(NubType to)
|
||||
{
|
||||
if (!Cache.TryGetValue(to, out var ptr))
|
||||
Cache[to] = ptr = new NubTypeArray(to);
|
||||
|
||||
return ptr;
|
||||
}
|
||||
|
||||
public NubType ElementType { get; }
|
||||
|
||||
private NubTypeArray(NubType elementType)
|
||||
{
|
||||
ElementType = elementType;
|
||||
}
|
||||
|
||||
public override string ToString() => $"[]{ElementType}";
|
||||
}
|
||||
|
||||
public class TypeEncoder
|
||||
{
|
||||
public static string Encode(NubType type)
|
||||
{
|
||||
return new TypeEncoder().EncodeRoot(type);
|
||||
}
|
||||
|
||||
private TypeEncoder()
|
||||
{
|
||||
}
|
||||
|
||||
private string EncodeRoot(NubType type)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Encode(type, sb);
|
||||
EncodeType(sb, type);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static void Encode(NubType type, StringBuilder sb)
|
||||
private void EncodeType(StringBuilder sb, NubType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
@@ -192,47 +320,81 @@ static class TypeEncoder
|
||||
break;
|
||||
|
||||
case NubTypeUInt u:
|
||||
sb.Append("U(").Append(u.Width).Append(')');
|
||||
sb.Append($"U(");
|
||||
sb.Append(u.Width);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeSInt s:
|
||||
sb.Append("I(").Append(s.Width).Append(')');
|
||||
sb.Append($"I(");
|
||||
sb.Append(s.Width);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeString:
|
||||
sb.Append('S');
|
||||
break;
|
||||
|
||||
case NubTypeChar:
|
||||
sb.Append('C');
|
||||
break;
|
||||
|
||||
case NubTypePointer p:
|
||||
sb.Append("P(");
|
||||
Encode(p.To, sb);
|
||||
EncodeType(sb, p.To);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeStruct st:
|
||||
sb.Append("T(");
|
||||
sb.Append(st.Module).Append("::").Append(st.Name);
|
||||
sb.Append(',').Append(st.Packed ? '1' : '0');
|
||||
sb.Append('{');
|
||||
for (int i = 0; i < st.Fields.Count; i++)
|
||||
{
|
||||
var field = st.Fields[i];
|
||||
sb.Append(field.Name).Append(':');
|
||||
Encode(field.Type, sb);
|
||||
if (i < st.Fields.Count - 1)
|
||||
sb.Append(',');
|
||||
}
|
||||
sb.Append("})");
|
||||
sb.Append("TN(");
|
||||
sb.Append(st.Module);
|
||||
sb.Append(':');
|
||||
sb.Append(st.Name);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeEnum e:
|
||||
sb.Append("EN(");
|
||||
sb.Append(e.Module);
|
||||
sb.Append(':');
|
||||
sb.Append(e.Name);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeEnumVariant ev:
|
||||
sb.Append("EV(");
|
||||
sb.Append(ev.EnumType.Module);
|
||||
sb.Append(':');
|
||||
sb.Append(ev.EnumType.Name);
|
||||
sb.Append(':');
|
||||
sb.Append(ev.Variant);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeFunc fn:
|
||||
sb.Append("F(");
|
||||
foreach (var parameter in fn.Parameters)
|
||||
for (int i = 0; i < fn.Parameters.Count; i++)
|
||||
{
|
||||
sb.Append(Encode(parameter));
|
||||
sb.Append(',');
|
||||
EncodeType(sb, fn.Parameters[i]);
|
||||
}
|
||||
sb.Append(Encode(fn.ReturnType));
|
||||
EncodeType(sb, fn.ReturnType);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeAnonymousStruct s:
|
||||
sb.Append("TA(");
|
||||
foreach (var field in s.Fields)
|
||||
{
|
||||
sb.Append(field.Name);
|
||||
sb.Append(':');
|
||||
EncodeType(sb, field.Type);
|
||||
}
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
case NubTypeArray a:
|
||||
sb.Append("A(");
|
||||
EncodeType(sb, a.ElementType);
|
||||
sb.Append(')');
|
||||
break;
|
||||
|
||||
@@ -240,13 +402,19 @@ static class TypeEncoder
|
||||
throw new NotSupportedException(type.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private class Definition(int index)
|
||||
{
|
||||
public int Index { get; } = index;
|
||||
public string? Encoded { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
class TypeDecoder
|
||||
public class TypeDecoder
|
||||
{
|
||||
public static NubType Decode(string encoded)
|
||||
{
|
||||
return new TypeDecoder(encoded).Decode();
|
||||
return new TypeDecoder(encoded).DecodeType();
|
||||
}
|
||||
|
||||
private TypeDecoder(string encoded)
|
||||
@@ -255,158 +423,249 @@ class TypeDecoder
|
||||
}
|
||||
|
||||
private readonly string encoded;
|
||||
private int pos;
|
||||
private int index = 0;
|
||||
|
||||
private NubType Decode()
|
||||
private NubType DecodeType()
|
||||
{
|
||||
return Parse();
|
||||
}
|
||||
|
||||
private NubType Parse()
|
||||
{
|
||||
if (pos >= encoded.Length)
|
||||
throw new InvalidOperationException("Unexpected end of string");
|
||||
|
||||
char c = encoded[pos++];
|
||||
return c switch
|
||||
var start = Consume();
|
||||
return start switch
|
||||
{
|
||||
'V' => NubTypeVoid.Instance,
|
||||
'B' => NubTypeBool.Instance,
|
||||
'U' => DecodeUInt(),
|
||||
'I' => DecodeSInt(),
|
||||
'S' => NubTypeString.Instance,
|
||||
'U' => ParseUInt(),
|
||||
'I' => ParseSInt(),
|
||||
'P' => ParsePointer(),
|
||||
'T' => ParseStruct(),
|
||||
'F' => ParseFunc(),
|
||||
_ => throw new NotSupportedException($"Unknown type code '{c}' at position {pos - 1}")
|
||||
'C' => NubTypeChar.Instance,
|
||||
'P' => DecodePointer(),
|
||||
'F' => DecodeFunc(),
|
||||
'T' => DecodeStruct(),
|
||||
'E' => DecodeEnum(),
|
||||
'A' => DecodeArray(),
|
||||
_ => throw new Exception($"'{start}' is not a valid start to a type")
|
||||
};
|
||||
}
|
||||
|
||||
private NubTypeUInt ParseUInt()
|
||||
private NubTypeUInt DecodeUInt()
|
||||
{
|
||||
ExpectChar('(');
|
||||
int width = ReadNumber();
|
||||
ExpectChar(')');
|
||||
Expect('(');
|
||||
var width = ExpectInt();
|
||||
Expect(')');
|
||||
return NubTypeUInt.Get(width);
|
||||
}
|
||||
|
||||
private NubTypeSInt ParseSInt()
|
||||
private NubTypeSInt DecodeSInt()
|
||||
{
|
||||
ExpectChar('(');
|
||||
int width = ReadNumber();
|
||||
ExpectChar(')');
|
||||
Expect('(');
|
||||
var width = ExpectInt();
|
||||
Expect(')');
|
||||
return NubTypeSInt.Get(width);
|
||||
}
|
||||
|
||||
private NubTypePointer ParsePointer()
|
||||
private NubTypePointer DecodePointer()
|
||||
{
|
||||
ExpectChar('(');
|
||||
var to = Parse();
|
||||
ExpectChar(')');
|
||||
Expect('(');
|
||||
var to = DecodeType();
|
||||
Expect(')');
|
||||
return NubTypePointer.Get(to);
|
||||
}
|
||||
|
||||
private NubTypeStruct ParseStruct()
|
||||
private NubTypeFunc DecodeFunc()
|
||||
{
|
||||
ExpectChar('(');
|
||||
int start = pos;
|
||||
while (pos < encoded.Length && encoded[pos] != ',' && encoded[pos] != '{') pos++;
|
||||
var fullName = encoded[start..pos];
|
||||
var parts = fullName.Split("::");
|
||||
if (parts.Length != 2)
|
||||
throw new InvalidOperationException($"Invalid struct name: {fullName}");
|
||||
var types = new List<NubType>();
|
||||
|
||||
string module = parts[0], name = parts[1];
|
||||
|
||||
bool packed = false;
|
||||
if (encoded[pos] == ',')
|
||||
Expect('(');
|
||||
while (!TryExpect(')'))
|
||||
{
|
||||
pos += 1;
|
||||
packed = encoded[pos += 1] == '1';
|
||||
types.Add(DecodeType());
|
||||
}
|
||||
|
||||
var st = new NubTypeStruct(module, name, packed);
|
||||
|
||||
ExpectChar('{');
|
||||
|
||||
var fields = new List<NubTypeStruct.Field>();
|
||||
while (encoded[pos] != '}')
|
||||
{
|
||||
int nameStart = pos;
|
||||
while (encoded[pos] != ':') pos += 1;
|
||||
string fieldName = encoded[nameStart..pos];
|
||||
pos += 1;
|
||||
|
||||
var fieldType = Parse();
|
||||
fields.Add(new NubTypeStruct.Field(fieldName, fieldType));
|
||||
|
||||
if (encoded[pos] == ',') pos += 1;
|
||||
}
|
||||
|
||||
ExpectChar('}');
|
||||
ExpectChar(')');
|
||||
|
||||
st.ResolveFields(fields);
|
||||
return st;
|
||||
return NubTypeFunc.Get(types.Take(types.Count - 1).ToList(), types.Last());
|
||||
}
|
||||
|
||||
private NubTypeFunc ParseFunc()
|
||||
private NubType DecodeStruct()
|
||||
{
|
||||
ExpectChar('(');
|
||||
var parameters = new List<NubType>();
|
||||
while (true)
|
||||
|
||||
if (TryExpect('A'))
|
||||
{
|
||||
if (encoded[pos] == ')')
|
||||
var sb = new StringBuilder();
|
||||
var fields = new List<NubTypeAnonymousStruct.Field>();
|
||||
|
||||
Expect('(');
|
||||
while (!TryExpect(')'))
|
||||
{
|
||||
pos++;
|
||||
while (!TryExpect(':'))
|
||||
{
|
||||
sb.Append(Consume());
|
||||
}
|
||||
|
||||
var name = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
var type = DecodeType();
|
||||
|
||||
fields.Add(new NubTypeAnonymousStruct.Field(name, type));
|
||||
}
|
||||
|
||||
return NubTypeAnonymousStruct.Get(fields);
|
||||
}
|
||||
|
||||
if (TryExpect('N'))
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
Expect('(');
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var module = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
while (!TryExpect(')'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var name = sb.ToString();
|
||||
|
||||
return NubTypeStruct.Get(module, name);
|
||||
}
|
||||
|
||||
throw new Exception("Expected 'A' or 'N'");
|
||||
}
|
||||
|
||||
private NubType DecodeEnum()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
if (TryExpect('V'))
|
||||
{
|
||||
Expect('(');
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var module = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var name = sb.ToString();
|
||||
|
||||
while (!TryExpect(')'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var variant = sb.ToString();
|
||||
|
||||
return NubTypeEnumVariant.Get(NubTypeEnum.Get(module, name), variant);
|
||||
}
|
||||
else if (TryExpect('N'))
|
||||
{
|
||||
Expect('(');
|
||||
while (!TryExpect(':'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var module = sb.ToString();
|
||||
sb.Clear();
|
||||
|
||||
while (!TryExpect(')'))
|
||||
sb.Append(Consume());
|
||||
|
||||
var name = sb.ToString();
|
||||
|
||||
return NubTypeEnum.Get(module, name);
|
||||
}
|
||||
|
||||
throw new Exception($"Expected 'V' or 'N'");
|
||||
}
|
||||
|
||||
private NubTypeArray DecodeArray()
|
||||
{
|
||||
Expect('(');
|
||||
var elementType = DecodeType();
|
||||
Expect(')');
|
||||
return NubTypeArray.Get(elementType);
|
||||
}
|
||||
|
||||
private bool TryPeek(out char c)
|
||||
{
|
||||
if (index >= encoded.Length)
|
||||
{
|
||||
c = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
c = encoded[index];
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryConsume(out char c)
|
||||
{
|
||||
if (index >= encoded.Length)
|
||||
{
|
||||
c = '\0';
|
||||
return false;
|
||||
}
|
||||
|
||||
c = encoded[index];
|
||||
index += 1;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private char Consume()
|
||||
{
|
||||
if (!TryConsume(out var c))
|
||||
throw new Exception("Unexpected end of string");
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
private bool TryExpect(char c)
|
||||
{
|
||||
if (index >= encoded.Length)
|
||||
return false;
|
||||
|
||||
if (encoded[index] != c)
|
||||
return false;
|
||||
|
||||
Consume();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Expect(char c)
|
||||
{
|
||||
if (!TryExpect(c))
|
||||
throw new Exception($"Expected '{c}'");
|
||||
}
|
||||
|
||||
private int ExpectInt()
|
||||
{
|
||||
var buf = string.Empty;
|
||||
|
||||
while (TryPeek(out var c))
|
||||
{
|
||||
if (!char.IsDigit(c))
|
||||
break;
|
||||
}
|
||||
|
||||
var param = Parse();
|
||||
parameters.Add(param);
|
||||
|
||||
if (encoded[pos] == ',')
|
||||
{
|
||||
pos += 1;
|
||||
}
|
||||
else if (encoded[pos] == ')')
|
||||
{
|
||||
pos += 1;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException($"Unexpected char '{encoded[pos]}' in function type at {pos}");
|
||||
}
|
||||
buf += Consume();
|
||||
}
|
||||
|
||||
if (parameters.Count == 0)
|
||||
throw new InvalidOperationException("Function must have a return type");
|
||||
|
||||
var returnType = parameters[^1];
|
||||
var paramTypes = parameters.Take(parameters.Count - 1).ToList();
|
||||
|
||||
return NubTypeFunc.Get(paramTypes, returnType);
|
||||
}
|
||||
|
||||
private void ExpectChar(char expected)
|
||||
{
|
||||
if (pos >= encoded.Length || encoded[pos] != expected)
|
||||
throw new InvalidOperationException($"Expected '{expected}' at position {pos}");
|
||||
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
private int ReadNumber()
|
||||
{
|
||||
int start = pos;
|
||||
while (pos < encoded.Length && char.IsDigit(encoded[pos])) pos += 1;
|
||||
if (start == pos) throw new InvalidOperationException($"Expected number at position {start}");
|
||||
return int.Parse(encoded[start..pos]);
|
||||
return int.Parse(buf);
|
||||
}
|
||||
}
|
||||
|
||||
static class Hashing
|
||||
public class NubTypeJsonConverter : JsonConverter<NubType>
|
||||
{
|
||||
public override NubType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
return TypeDecoder.Decode(reader.GetString()!);
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, NubType value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStringValue(TypeEncoder.Encode(value));
|
||||
}
|
||||
}
|
||||
|
||||
public static class Hashing
|
||||
{
|
||||
public static ulong Fnv1a64(string text)
|
||||
{
|
||||
@@ -424,14 +683,14 @@ static class Hashing
|
||||
}
|
||||
}
|
||||
|
||||
static class SymbolNameGen
|
||||
public static class NameMangler
|
||||
{
|
||||
public static string Exported(string module, string function, NubType type)
|
||||
public static string Mangle(string module, string name, NubType type)
|
||||
{
|
||||
var canonical = TypeEncoder.Encode(type);
|
||||
var hash = Hashing.Fnv1a64(canonical);
|
||||
|
||||
return $"nub_{Sanitize(module)}_{Sanitize(function)}_{hash:x16}";
|
||||
return $"nub_{Sanitize(module)}_{Sanitize(name)}_{hash:x16}";
|
||||
}
|
||||
|
||||
private static string Sanitize(string s)
|
||||
|
||||
@@ -53,55 +53,54 @@ public class Parser
|
||||
|
||||
Dictionary<Keyword, TokenKeyword> modifiers = [];
|
||||
|
||||
while (true)
|
||||
while (Peek() is TokenKeyword keyword)
|
||||
{
|
||||
if (Peek() is TokenKeyword keyword)
|
||||
switch (keyword.Keyword)
|
||||
{
|
||||
switch (keyword.Keyword)
|
||||
{
|
||||
case Keyword.Export:
|
||||
Next();
|
||||
modifiers[Keyword.Export] = keyword;
|
||||
break;
|
||||
case Keyword.Packed:
|
||||
Next();
|
||||
modifiers[Keyword.Packed] = keyword;
|
||||
break;
|
||||
default:
|
||||
goto modifier_done;
|
||||
}
|
||||
case Keyword.Export:
|
||||
Next();
|
||||
modifiers[Keyword.Export] = keyword;
|
||||
break;
|
||||
case Keyword.Packed:
|
||||
Next();
|
||||
modifiers[Keyword.Packed] = keyword;
|
||||
break;
|
||||
case Keyword.Extern:
|
||||
Next();
|
||||
modifiers[Keyword.Extern] = keyword;
|
||||
break;
|
||||
default:
|
||||
goto modifier_done;
|
||||
}
|
||||
}
|
||||
|
||||
modifier_done:
|
||||
modifier_done:
|
||||
|
||||
if (TryExpectKeyword(Keyword.Func))
|
||||
{
|
||||
var exported = modifiers.Remove(Keyword.Export);
|
||||
var @extern = modifiers.Remove(Keyword.Extern);
|
||||
|
||||
foreach (var modifier in modifiers)
|
||||
// todo(nub31): Add to diagnostics instead of throwing
|
||||
throw new CompileException(Diagnostic.Error("Invalid modifier for function").At(fileName, modifier.Value).Build());
|
||||
throw BasicError("Invalid modifier for function", modifier.Value);
|
||||
|
||||
var name = ExpectIdent();
|
||||
var parameters = new List<NodeDefinitionFunc.Param>();
|
||||
var parameters = ParseFuncParameters();
|
||||
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
while (!TryExpectSymbol(Symbol.CloseParen))
|
||||
NodeType? returnType = null;
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
returnType = ParseType();
|
||||
|
||||
if (@extern)
|
||||
{
|
||||
var paramStartIndex = index;
|
||||
var parameterName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var parameterType = ParseType();
|
||||
parameters.Add(new NodeDefinitionFunc.Param(TokensFrom(paramStartIndex), parameterName, parameterType));
|
||||
return new NodeDefinitionExternFunc(TokensFrom(startIndex), exported, name, parameters, returnType);
|
||||
}
|
||||
else
|
||||
{
|
||||
var body = ParseStatement();
|
||||
return new NodeDefinitionFunc(TokensFrom(startIndex), exported, name, parameters, body, returnType);
|
||||
}
|
||||
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var returnType = ParseType();
|
||||
|
||||
var body = ParseStatement();
|
||||
|
||||
return new NodeDefinitionFunc(TokensFrom(startIndex), exported, name, parameters, body, returnType);
|
||||
}
|
||||
|
||||
if (TryExpectKeyword(Keyword.Struct))
|
||||
@@ -111,7 +110,7 @@ public class Parser
|
||||
|
||||
foreach (var modifier in modifiers)
|
||||
// todo(nub31): Add to diagnostics instead of throwing
|
||||
throw new CompileException(Diagnostic.Error("Invalid modifier for struct").At(fileName, modifier.Value).Build());
|
||||
throw BasicError("Invalid modifier for struct", modifier.Value);
|
||||
|
||||
var name = ExpectIdent();
|
||||
var fields = new List<NodeDefinitionStruct.Field>();
|
||||
@@ -123,19 +122,49 @@ public class Parser
|
||||
var fieldName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var fieldType = ParseType();
|
||||
TryExpectSymbol(Symbol.Comma);
|
||||
fields.Add(new NodeDefinitionStruct.Field(TokensFrom(fieldStartIndex), fieldName, fieldType));
|
||||
}
|
||||
|
||||
return new NodeDefinitionStruct(TokensFrom(startIndex), exported, packed, name, fields);
|
||||
}
|
||||
|
||||
if (TryExpectKeyword(Keyword.Enum))
|
||||
{
|
||||
var exported = modifiers.Remove(Keyword.Export);
|
||||
|
||||
foreach (var modifier in modifiers)
|
||||
// todo(nub31): Add to diagnostics instead of throwing
|
||||
throw BasicError("Invalid modifier for struct", modifier.Value);
|
||||
|
||||
var name = ExpectIdent();
|
||||
var variants = new List<NodeDefinitionEnum.Variant>();
|
||||
|
||||
ExpectSymbol(Symbol.OpenCurly);
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var variantsStartIndex = index;
|
||||
var variantName = ExpectIdent();
|
||||
|
||||
NodeType? variantType = null;
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
variantType = ParseType();
|
||||
|
||||
TryExpectSymbol(Symbol.Comma);
|
||||
|
||||
variants.Add(new NodeDefinitionEnum.Variant(TokensFrom(variantsStartIndex), variantName, variantType));
|
||||
}
|
||||
|
||||
return new NodeDefinitionEnum(TokensFrom(startIndex), exported, name, variants);
|
||||
}
|
||||
|
||||
if (TryExpectKeyword(Keyword.Let))
|
||||
{
|
||||
var exported = modifiers.Remove(Keyword.Export);
|
||||
|
||||
foreach (var modifier in modifiers)
|
||||
// todo(nub31): Add to diagnostics instead of throwing
|
||||
throw new CompileException(Diagnostic.Error("Invalid modifier for global variable").At(fileName, modifier.Value).Build());
|
||||
throw BasicError("Invalid modifier for global variable", modifier.Value);
|
||||
|
||||
var name = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
@@ -144,7 +173,36 @@ public class Parser
|
||||
return new NodeDefinitionGlobalVariable(TokensFrom(startIndex), exported, name, type);
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error("Not a valid definition").At(fileName, Peek()).Build());
|
||||
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()
|
||||
@@ -162,17 +220,31 @@ public class Parser
|
||||
|
||||
if (TryExpectKeyword(Keyword.Return))
|
||||
{
|
||||
var value = ParseExpression();
|
||||
NodeExpression? value = null;
|
||||
|
||||
if (Peek() is TokenIdent token && token.Ident == "void")
|
||||
{
|
||||
Next();
|
||||
}
|
||||
else
|
||||
{
|
||||
value = ParseExpression();
|
||||
}
|
||||
|
||||
return new NodeStatementReturn(TokensFrom(startIndex), value);
|
||||
}
|
||||
|
||||
if (TryExpectKeyword(Keyword.Let))
|
||||
{
|
||||
var name = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var type = ParseType();
|
||||
|
||||
NodeType? type = null;
|
||||
if (TryExpectSymbol(Symbol.Colon))
|
||||
type = ParseType();
|
||||
|
||||
ExpectSymbol(Symbol.Equal);
|
||||
var value = ParseExpression();
|
||||
|
||||
return new NodeStatementVariableDeclaration(TokensFrom(startIndex), name, type, value);
|
||||
}
|
||||
|
||||
@@ -191,19 +263,48 @@ 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);
|
||||
}
|
||||
|
||||
var target = ParseExpression();
|
||||
|
||||
if (TryExpectSymbol(Symbol.Equal))
|
||||
if (TryExpectKeyword(Keyword.For))
|
||||
{
|
||||
var value = ParseExpression();
|
||||
return new NodeStatementAssignment(TokensFrom(startIndex), target, value);
|
||||
var variableName = ExpectIdent();
|
||||
ExpectKeyword(Keyword.In);
|
||||
var array = ParseExpression();
|
||||
var block = ParseStatement();
|
||||
return new NodeStatementFor(TokensFrom(startIndex), variableName, array, block);
|
||||
}
|
||||
|
||||
return new NodeStatementExpression(TokensFrom(startIndex), target);
|
||||
if (TryExpectKeyword(Keyword.Match))
|
||||
{
|
||||
var target = ParseExpression();
|
||||
var cases = new List<NodeStatementMatch.Case>();
|
||||
|
||||
ExpectSymbol(Symbol.OpenCurly);
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var caseStartIndex = index;
|
||||
var variant = ExpectIdent();
|
||||
TryExpectIdent(out var variableName);
|
||||
var body = ParseStatement();
|
||||
cases.Add(new NodeStatementMatch.Case(TokensFrom(caseStartIndex), variant, variableName, body));
|
||||
}
|
||||
|
||||
return new NodeStatementMatch(TokensFrom(startIndex), target, cases);
|
||||
}
|
||||
|
||||
{
|
||||
var target = ParseExpression();
|
||||
|
||||
if (TryExpectSymbol(Symbol.Equal))
|
||||
{
|
||||
var value = ParseExpression();
|
||||
return new NodeStatementAssignment(TokensFrom(startIndex), target, value);
|
||||
}
|
||||
|
||||
return new NodeStatementExpression(TokensFrom(startIndex), target);
|
||||
}
|
||||
}
|
||||
|
||||
private NodeExpression ParseExpression(int minPrecedence = -1)
|
||||
@@ -271,6 +372,33 @@ 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>();
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var initializerStartIndex = startIndex;
|
||||
var fieldName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Equal);
|
||||
var fieldValue = ParseExpression();
|
||||
initializers.Add(new NodeExpressionStructLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue));
|
||||
}
|
||||
|
||||
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), null, initializers);
|
||||
}
|
||||
else if (TryExpectSymbol(Symbol.Bang))
|
||||
{
|
||||
var target = ParseExpression();
|
||||
@@ -290,39 +418,63 @@ public class Parser
|
||||
}
|
||||
else if (TryExpectIdent(out var ident))
|
||||
{
|
||||
if (TryExpectSymbol(Symbol.ColonColon))
|
||||
List<TokenIdent> sections = [ident];
|
||||
|
||||
while (TryExpectSymbol(Symbol.ColonColon))
|
||||
{
|
||||
var name = ExpectIdent();
|
||||
expr = new NodeExpressionModuleIdent(TokensFrom(startIndex), ident, name);
|
||||
sections.Add(ExpectIdent());
|
||||
}
|
||||
|
||||
expr = new NodeExpressionIdent(TokensFrom(startIndex), sections);
|
||||
}
|
||||
else if (TryExpectKeyword(Keyword.New))
|
||||
{
|
||||
var type = ParseType();
|
||||
|
||||
if (type is NodeTypeString)
|
||||
{
|
||||
ExpectSymbol(Symbol.OpenParen);
|
||||
var value = ParseExpression();
|
||||
ExpectSymbol(Symbol.CloseParen);
|
||||
|
||||
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;
|
||||
var fieldName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Equal);
|
||||
var fieldValue = ParseExpression();
|
||||
initializers.Add(new NodeExpressionStructLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue));
|
||||
}
|
||||
|
||||
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), null, initializers);
|
||||
}
|
||||
else
|
||||
{
|
||||
expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), namedType, null);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
expr = new NodeExpressionLocalIdent(TokensFrom(startIndex), ident);
|
||||
throw BasicError($"Expected named type or string", type);
|
||||
}
|
||||
}
|
||||
else if (TryExpectKeyword(Keyword.Struct))
|
||||
{
|
||||
var module = ExpectIdent();
|
||||
ExpectSymbol(Symbol.ColonColon);
|
||||
var name = ExpectIdent();
|
||||
|
||||
var initializers = new List<NodeExpressionStructLiteral.Initializer>();
|
||||
|
||||
ExpectSymbol(Symbol.OpenCurly);
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var initializerStartIndex = startIndex;
|
||||
var fieldName = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Equal);
|
||||
var fieldValue = ParseExpression();
|
||||
initializers.Add(new NodeExpressionStructLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue));
|
||||
}
|
||||
|
||||
expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), module, name, initializers);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CompileException(Diagnostic.Error("Expected start of expression").At(fileName, Peek()).Build());
|
||||
throw BasicError("Expected start of expression", Peek());
|
||||
}
|
||||
|
||||
while (true)
|
||||
@@ -337,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);
|
||||
}
|
||||
@@ -376,6 +531,28 @@ public class Parser
|
||||
return new NodeTypeFunc(TokensFrom(startIndex), parameters, returnType);
|
||||
}
|
||||
|
||||
if (TryExpectSymbol(Symbol.OpenCurly))
|
||||
{
|
||||
var fields = new List<NodeTypeAnonymousStruct.Field>();
|
||||
|
||||
while (!TryExpectSymbol(Symbol.CloseCurly))
|
||||
{
|
||||
var name = ExpectIdent();
|
||||
ExpectSymbol(Symbol.Colon);
|
||||
var type = ParseType();
|
||||
fields.Add(new NodeTypeAnonymousStruct.Field(name, type));
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -384,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":
|
||||
@@ -394,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":
|
||||
@@ -403,13 +586,18 @@ public class Parser
|
||||
case "u64":
|
||||
return new NodeTypeUInt(TokensFrom(startIndex), 64);
|
||||
default:
|
||||
ExpectSymbol(Symbol.ColonColon);
|
||||
var name = ExpectIdent();
|
||||
return new NodeTypeCustom(TokensFrom(startIndex), ident, name);
|
||||
List<TokenIdent> secitons = [ident];
|
||||
while (TryExpectSymbol(Symbol.ColonColon))
|
||||
{
|
||||
ident = ExpectIdent();
|
||||
secitons.Add(ident);
|
||||
}
|
||||
|
||||
return new NodeTypeNamed(TokensFrom(startIndex), secitons);
|
||||
}
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error("Expected type").At(fileName, Peek()).Build());
|
||||
throw BasicError("Expected type", Peek());
|
||||
}
|
||||
|
||||
private List<Token> TokensFrom(int startIndex)
|
||||
@@ -425,7 +613,7 @@ public class Parser
|
||||
return;
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error($"Expected '{keyword.AsString()}'").At(fileName, Peek()).Build());
|
||||
throw BasicError($"Expected '{keyword.AsString()}'", Peek());
|
||||
}
|
||||
|
||||
private bool TryExpectKeyword(Keyword keyword)
|
||||
@@ -447,7 +635,7 @@ public class Parser
|
||||
return;
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error($"Expected '{symbol.AsString()}'").At(fileName, Peek()).Build());
|
||||
throw BasicError($"Expected '{symbol.AsString()}'", Peek());
|
||||
}
|
||||
|
||||
private bool TryExpectSymbol(Symbol symbol)
|
||||
@@ -469,7 +657,7 @@ public class Parser
|
||||
return token;
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error("Expected identifier").At(fileName, Peek()).Build());
|
||||
throw BasicError("Expected identifier", Peek());
|
||||
}
|
||||
|
||||
private bool TryExpectIdent([NotNullWhen(true)] out TokenIdent? ident)
|
||||
@@ -527,7 +715,7 @@ public class Parser
|
||||
private void Next()
|
||||
{
|
||||
if (index >= tokens.Count)
|
||||
throw new CompileException(Diagnostic.Error("Unexpected end of tokens").At(fileName, Peek()).Build());
|
||||
throw BasicError("Unexpected end of tokens", Peek());
|
||||
|
||||
index += 1;
|
||||
}
|
||||
@@ -600,6 +788,16 @@ public class Parser
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private CompileException BasicError(string message, Token? 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());
|
||||
}
|
||||
}
|
||||
|
||||
public class Ast(string fileName, TokenIdent moduleName, List<NodeDefinition> definitions)
|
||||
@@ -616,13 +814,21 @@ public abstract class Node(List<Token> tokens)
|
||||
|
||||
public abstract class NodeDefinition(List<Token> tokens) : Node(tokens);
|
||||
|
||||
public class NodeDefinitionFunc(List<Token> tokens, bool exported, TokenIdent name, List<NodeDefinitionFunc.Param> parameters, NodeStatement body, NodeType returnType) : NodeDefinition(tokens)
|
||||
public class NodeDefinitionExternFunc(List<Token> tokens, bool exported, TokenIdent name, List<NodeDefinitionFunc.Param> parameters, NodeType? returnType) : NodeDefinition(tokens)
|
||||
{
|
||||
public bool Exported { get; } = exported;
|
||||
public TokenIdent Name { get; } = name;
|
||||
public List<NodeDefinitionFunc.Param> Parameters { get; } = parameters;
|
||||
public NodeType? ReturnType { get; } = returnType;
|
||||
}
|
||||
|
||||
public class NodeDefinitionFunc(List<Token> tokens, bool exported, TokenIdent name, List<NodeDefinitionFunc.Param> parameters, NodeStatement body, NodeType? returnType) : NodeDefinition(tokens)
|
||||
{
|
||||
public bool Exported { get; } = exported;
|
||||
public TokenIdent Name { get; } = name;
|
||||
public List<Param> Parameters { get; } = parameters;
|
||||
public NodeStatement Body { get; } = body;
|
||||
public NodeType ReturnType { get; } = returnType;
|
||||
public NodeType? ReturnType { get; } = returnType;
|
||||
|
||||
public class Param(List<Token> tokens, TokenIdent name, NodeType type) : Node(tokens)
|
||||
{
|
||||
@@ -645,6 +851,26 @@ public class NodeDefinitionStruct(List<Token> tokens, bool exported, bool packed
|
||||
}
|
||||
}
|
||||
|
||||
public class NodeDefinitionEnum(List<Token> tokens, bool exported, TokenIdent name, List<NodeDefinitionEnum.Variant> variants) : NodeDefinition(tokens)
|
||||
{
|
||||
public bool Exported { get; } = exported;
|
||||
public TokenIdent Name { get; } = name;
|
||||
public List<Variant> Variants { get; } = variants;
|
||||
|
||||
public class Variant(List<Token> tokens, TokenIdent name, NodeType? type) : Node(tokens)
|
||||
{
|
||||
public TokenIdent Name { get; } = name;
|
||||
public NodeType? Type { get; } = type;
|
||||
}
|
||||
}
|
||||
|
||||
public class NodeDefinitionExternGlobalVariable(List<Token> tokens, bool exported, TokenIdent name, NodeType type) : NodeDefinition(tokens)
|
||||
{
|
||||
public bool Exported { get; } = exported;
|
||||
public TokenIdent Name { get; } = name;
|
||||
public NodeType Type { get; } = type;
|
||||
}
|
||||
|
||||
public class NodeDefinitionGlobalVariable(List<Token> tokens, bool exported, TokenIdent name, NodeType type) : NodeDefinition(tokens)
|
||||
{
|
||||
public bool Exported { get; } = exported;
|
||||
@@ -664,15 +890,15 @@ public class NodeStatementExpression(List<Token> tokens, NodeExpression expressi
|
||||
public NodeExpression Expression { get; } = expression;
|
||||
}
|
||||
|
||||
public class NodeStatementReturn(List<Token> tokens, NodeExpression value) : NodeStatement(tokens)
|
||||
public class NodeStatementReturn(List<Token> tokens, NodeExpression? value) : NodeStatement(tokens)
|
||||
{
|
||||
public NodeExpression Value { get; } = value;
|
||||
public NodeExpression? Value { get; } = value;
|
||||
}
|
||||
|
||||
public class NodeStatementVariableDeclaration(List<Token> tokens, TokenIdent name, NodeType type, NodeExpression value) : NodeStatement(tokens)
|
||||
public class NodeStatementVariableDeclaration(List<Token> tokens, TokenIdent name, NodeType? type, NodeExpression value) : NodeStatement(tokens)
|
||||
{
|
||||
public TokenIdent Name { get; } = name;
|
||||
public NodeType Type { get; } = type;
|
||||
public NodeType? Type { get; } = type;
|
||||
public NodeExpression Value { get; } = value;
|
||||
}
|
||||
|
||||
@@ -689,10 +915,30 @@ public class NodeStatementIf(List<Token> tokens, NodeExpression condition, NodeS
|
||||
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 NodeStatement Block { get; } = block;
|
||||
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 TokenIdent Variant { get; } = type;
|
||||
public TokenIdent? VariableName { get; } = variableName;
|
||||
public NodeStatement Body { get; } = body;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class NodeExpression(List<Token> tokens) : Node(tokens);
|
||||
@@ -712,10 +958,9 @@ public class NodeExpressionBoolLiteral(List<Token> tokens, TokenBoolLiteral valu
|
||||
public TokenBoolLiteral Value { get; } = value;
|
||||
}
|
||||
|
||||
public class NodeExpressionStructLiteral(List<Token> tokens, TokenIdent module, TokenIdent name, List<NodeExpressionStructLiteral.Initializer> initializers) : NodeExpression(tokens)
|
||||
public class NodeExpressionStructLiteral(List<Token> tokens, NodeTypeNamed? type, List<NodeExpressionStructLiteral.Initializer> initializers) : NodeExpression(tokens)
|
||||
{
|
||||
public TokenIdent Module { get; } = module;
|
||||
public TokenIdent Name { get; } = name;
|
||||
public NodeTypeNamed? Type { get; } = type;
|
||||
public List<Initializer> Initializers { get; } = initializers;
|
||||
|
||||
public class Initializer(List<Token> tokens, TokenIdent name, NodeExpression value) : Node(tokens)
|
||||
@@ -725,6 +970,22 @@ public class NodeExpressionStructLiteral(List<Token> tokens, TokenIdent module,
|
||||
}
|
||||
}
|
||||
|
||||
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 NodeExpression Value { get; } = value;
|
||||
}
|
||||
|
||||
public class NodeExpressionMemberAccess(List<Token> tokens, NodeExpression target, TokenIdent name) : NodeExpression(tokens)
|
||||
{
|
||||
public NodeExpression Target { get; } = target;
|
||||
@@ -737,15 +998,9 @@ public class NodeExpressionFuncCall(List<Token> tokens, NodeExpression target, L
|
||||
public List<NodeExpression> Parameters { get; } = parameters;
|
||||
}
|
||||
|
||||
public class NodeExpressionLocalIdent(List<Token> tokens, TokenIdent value) : NodeExpression(tokens)
|
||||
public class NodeExpressionIdent(List<Token> tokens, List<TokenIdent> sections) : NodeExpression(tokens)
|
||||
{
|
||||
public TokenIdent Value { get; } = value;
|
||||
}
|
||||
|
||||
public class NodeExpressionModuleIdent(List<Token> tokens, TokenIdent module, TokenIdent value) : NodeExpression(tokens)
|
||||
{
|
||||
public TokenIdent Module { get; } = module;
|
||||
public TokenIdent Value { get; } = value;
|
||||
public List<TokenIdent> Sections { get; } = sections;
|
||||
}
|
||||
|
||||
public class NodeExpressionBinary(List<Token> tokens, NodeExpression left, NodeExpressionBinary.Op operation, NodeExpression right) : NodeExpression(tokens)
|
||||
@@ -811,10 +1066,27 @@ public class NodeTypeBool(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 NodeTypeChar(List<Token> tokens) : NodeType(tokens);
|
||||
|
||||
public class NodeTypeNamed(List<Token> tokens, List<TokenIdent> sections) : NodeType(tokens)
|
||||
{
|
||||
public TokenIdent Module { get; } = module;
|
||||
public TokenIdent Name { get; } = name;
|
||||
public List<TokenIdent> Sections { get; } = sections;
|
||||
}
|
||||
|
||||
public class NodeTypeAnonymousStruct(List<Token> tokens, List<NodeTypeAnonymousStruct.Field> fields) : NodeType(tokens)
|
||||
{
|
||||
public List<Field> Fields { get; } = fields;
|
||||
|
||||
public class Field(TokenIdent name, NodeType type)
|
||||
{
|
||||
public TokenIdent Name { get; } = name;
|
||||
public NodeType Type { get; } = type;
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -826,4 +1098,4 @@ public class NodeTypeFunc(List<Token> tokens, List<NodeType> parameters, NodeTyp
|
||||
{
|
||||
public List<NodeType> Parameters { get; } = parameters;
|
||||
public NodeType ReturnType { get; } = returnType;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,8 +119,6 @@ foreach (var ast in asts)
|
||||
}
|
||||
}
|
||||
|
||||
var output = Generator.Emit(functions, moduleGraph, compileLib);
|
||||
|
||||
if (Directory.Exists(".build"))
|
||||
{
|
||||
CleanDirectory(".build");
|
||||
@@ -130,17 +128,36 @@ else
|
||||
Directory.CreateDirectory(".build");
|
||||
}
|
||||
|
||||
string? entryPoint = null;
|
||||
|
||||
if (!compileLib)
|
||||
{
|
||||
if (!moduleGraph.TryResolveIdentifier("main", "main", true, out var info) || info.Type is not NubTypeFunc entryPointType)
|
||||
{
|
||||
DiagnosticFormatter.Print(Diagnostic.Error("func main::main(): i32 is not defined. If you wanted to compile as a library, specify --type=lib").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!entryPointType.ReturnType.IsAssignableTo(NubTypeSInt.Get(32)))
|
||||
{
|
||||
DiagnosticFormatter.Print(Diagnostic.Error($"Entrypoint must return an i32 (currently '{entryPointType.ReturnType}')").Build(), Console.Error);
|
||||
return 1;
|
||||
}
|
||||
|
||||
entryPoint = info.MangledName;
|
||||
}
|
||||
|
||||
var outFile = Generator.Emit(functions, moduleGraph, entryPoint);
|
||||
|
||||
if (compileLib)
|
||||
{
|
||||
File.WriteAllText(".build/out.c", output);
|
||||
Process.Start("gcc", ["-Og", "-fvisibility=hidden", "-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", moduleGraph.CreateManifest());
|
||||
NubLib.Pack(".build/out.nublib", ".build/out.a", Manifest.Create(moduleGraph));
|
||||
}
|
||||
else
|
||||
{
|
||||
File.WriteAllText(".build/out.c", output);
|
||||
Process.Start("gcc", ["-Og", "-fvisibility=hidden", "-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;
|
||||
@@ -159,4 +176,4 @@ static void CleanDirectory(string dirName)
|
||||
CleanDirectory(subdir.FullName);
|
||||
subdir.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,332 +77,348 @@ public class Tokenizer
|
||||
switch (c)
|
||||
{
|
||||
case '0' when Peek(1) is 'x':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
|
||||
var parsed = BigInteger.Zero;
|
||||
var seenDigit = false;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!char.IsAsciiHexDigit(c))
|
||||
break;
|
||||
|
||||
seenDigit = true;
|
||||
parsed <<= 4;
|
||||
|
||||
Consume();
|
||||
parsed += c switch
|
||||
Consume();
|
||||
|
||||
var parsed = BigInteger.Zero;
|
||||
var seenDigit = false;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
>= '0' and <= '9' => c - '0',
|
||||
>= 'a' and <= 'f' => c - 'a' + 10,
|
||||
>= 'A' and <= 'F' => c - 'A' + 10,
|
||||
_ => 0
|
||||
};
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!char.IsAsciiHexDigit(c))
|
||||
break;
|
||||
|
||||
seenDigit = true;
|
||||
parsed <<= 4;
|
||||
|
||||
Consume();
|
||||
parsed += c switch
|
||||
{
|
||||
>= '0' and <= '9' => c - '0',
|
||||
>= 'a' and <= 'f' => c - 'a' + 10,
|
||||
>= 'A' and <= 'F' => c - 'A' + 10,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
|
||||
if (!seenDigit)
|
||||
throw new CompileException(Diagnostic.Error("Expected hexadecimal digits after 0x").At(fileName, line, startColumn, column - startColumn).Build());
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
|
||||
if (!seenDigit)
|
||||
throw new CompileException(Diagnostic.Error("Expected hexadecimal digits after 0x").At(fileName, line, startColumn, column - startColumn).Build());
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
case '0' when Peek(1) is 'b':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
|
||||
var parsed = BigInteger.Zero;
|
||||
var seenDigit = false;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
if (c == '_')
|
||||
Consume();
|
||||
Consume();
|
||||
|
||||
var parsed = BigInteger.Zero;
|
||||
var seenDigit = false;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c is not '0' and not '1')
|
||||
break;
|
||||
|
||||
seenDigit = true;
|
||||
parsed <<= 1;
|
||||
|
||||
if (Consume() == '1')
|
||||
parsed += BigInteger.One;
|
||||
}
|
||||
|
||||
if (c is not '0' and not '1')
|
||||
break;
|
||||
if (!seenDigit)
|
||||
throw new CompileException(Diagnostic.Error("Expected binary digits after 0b").At(fileName, line, startColumn, column - startColumn).Build());
|
||||
|
||||
seenDigit = true;
|
||||
parsed <<= 1;
|
||||
|
||||
if (Consume() == '1')
|
||||
parsed += BigInteger.One;
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
|
||||
if (!seenDigit)
|
||||
throw new CompileException(Diagnostic.Error("Expected binary digits after 0b").At(fileName, line, startColumn, column - startColumn).Build());
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
default:
|
||||
{
|
||||
var parsed = BigInteger.Zero;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
if (c == '_')
|
||||
var parsed = BigInteger.Zero;
|
||||
|
||||
while (TryPeek(out c))
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
if (c == '_')
|
||||
{
|
||||
Consume();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!char.IsDigit(c))
|
||||
break;
|
||||
|
||||
parsed *= 10;
|
||||
parsed += Consume() - '0';
|
||||
}
|
||||
|
||||
if (!char.IsDigit(c))
|
||||
break;
|
||||
|
||||
parsed *= 10;
|
||||
parsed += Consume() - '0';
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
|
||||
return new TokenIntLiteral(line, startColumn, column - startColumn, parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '"':
|
||||
{
|
||||
Consume();
|
||||
var buf = new StringBuilder();
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (!TryPeek(out c))
|
||||
throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 0).Build());
|
||||
|
||||
if (c == '"')
|
||||
break;
|
||||
|
||||
if (c == '\n')
|
||||
throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 1).Build());
|
||||
|
||||
buf.Append(Consume());
|
||||
}
|
||||
|
||||
Consume();
|
||||
return new TokenStringLiteral(line, startColumn, column - startColumn, buf.ToString());
|
||||
}
|
||||
|
||||
case '{':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenCurly);
|
||||
}
|
||||
case '}':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseCurly);
|
||||
}
|
||||
case '(':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenParen);
|
||||
}
|
||||
case ')':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseParen);
|
||||
}
|
||||
case ',':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Comma);
|
||||
}
|
||||
case '.':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Period);
|
||||
}
|
||||
case ':' when Peek(1) is ':':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ColonColon);
|
||||
}
|
||||
case ':':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Colon);
|
||||
}
|
||||
case '^':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Caret);
|
||||
}
|
||||
case '!' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.BangEqual);
|
||||
}
|
||||
case '!':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Bang);
|
||||
}
|
||||
case '=' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.EqualEqual);
|
||||
}
|
||||
case '=':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Equal);
|
||||
}
|
||||
case '<' when Peek(1) is '<':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanLessThan);
|
||||
}
|
||||
case '<' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanEqual);
|
||||
}
|
||||
case '<':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThan);
|
||||
}
|
||||
case '>' when Peek(1) is '>':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanGreaterThan);
|
||||
}
|
||||
case '>' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanEqual);
|
||||
}
|
||||
case '>':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThan);
|
||||
}
|
||||
case '+' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PlusEqual);
|
||||
}
|
||||
case '+':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Plus);
|
||||
}
|
||||
case '-' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.MinusEqual);
|
||||
}
|
||||
case '-':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Minus);
|
||||
}
|
||||
case '*' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.StarEqual);
|
||||
}
|
||||
case '*':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Star);
|
||||
}
|
||||
case '/' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlashEqual);
|
||||
}
|
||||
case '/':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlash);
|
||||
}
|
||||
case '%' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PercentEqual);
|
||||
}
|
||||
case '%':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Percent);
|
||||
}
|
||||
case '&' when Peek(1) is '&':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.AmpersandAmpersand);
|
||||
}
|
||||
case '&':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Ampersand);
|
||||
}
|
||||
case '|' when Peek(1) is '|':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PipePipe);
|
||||
}
|
||||
case '|':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Pipe);
|
||||
}
|
||||
default:
|
||||
{
|
||||
if (char.IsLetter(c) || c == '_')
|
||||
{
|
||||
Consume();
|
||||
var buf = new StringBuilder();
|
||||
|
||||
while (TryPeek(out c) && (char.IsLetterOrDigit(c) || c == '_'))
|
||||
buf.Append(Consume());
|
||||
|
||||
var value = buf.ToString();
|
||||
|
||||
return value switch
|
||||
while (true)
|
||||
{
|
||||
"func" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Func),
|
||||
"struct" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Struct),
|
||||
"packed" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Packed),
|
||||
"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),
|
||||
"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),
|
||||
"true" => new TokenBoolLiteral(line, startColumn, column - startColumn, true),
|
||||
"false" => new TokenBoolLiteral(line, startColumn, column - startColumn, false),
|
||||
_ => new TokenIdent(line, startColumn, column - startColumn, value)
|
||||
};
|
||||
if (!TryPeek(out c))
|
||||
throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 0).Build());
|
||||
|
||||
if (c == '"')
|
||||
break;
|
||||
|
||||
if (c == '\n')
|
||||
throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 1).Build());
|
||||
|
||||
buf.Append(Consume());
|
||||
}
|
||||
|
||||
Consume();
|
||||
return new TokenStringLiteral(line, startColumn, column - startColumn, buf.ToString());
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error($"Unexpected character '{c}'").At(fileName, line, column, 1).Build());
|
||||
}
|
||||
case '{':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenCurly);
|
||||
}
|
||||
case '}':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseCurly);
|
||||
}
|
||||
case '[':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenSquare);
|
||||
}
|
||||
case ']':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseSquare);
|
||||
}
|
||||
case '(':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenParen);
|
||||
}
|
||||
case ')':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseParen);
|
||||
}
|
||||
case ',':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Comma);
|
||||
}
|
||||
case '.':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Period);
|
||||
}
|
||||
case ':' when Peek(1) is ':':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ColonColon);
|
||||
}
|
||||
case ':':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Colon);
|
||||
}
|
||||
case '^':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Caret);
|
||||
}
|
||||
case '!' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.BangEqual);
|
||||
}
|
||||
case '!':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Bang);
|
||||
}
|
||||
case '=' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.EqualEqual);
|
||||
}
|
||||
case '=':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Equal);
|
||||
}
|
||||
case '<' when Peek(1) is '<':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanLessThan);
|
||||
}
|
||||
case '<' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanEqual);
|
||||
}
|
||||
case '<':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThan);
|
||||
}
|
||||
case '>' when Peek(1) is '>':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanGreaterThan);
|
||||
}
|
||||
case '>' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanEqual);
|
||||
}
|
||||
case '>':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThan);
|
||||
}
|
||||
case '+' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PlusEqual);
|
||||
}
|
||||
case '+':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Plus);
|
||||
}
|
||||
case '-' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.MinusEqual);
|
||||
}
|
||||
case '-':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Minus);
|
||||
}
|
||||
case '*' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.StarEqual);
|
||||
}
|
||||
case '*':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Star);
|
||||
}
|
||||
case '/' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlashEqual);
|
||||
}
|
||||
case '/':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlash);
|
||||
}
|
||||
case '%' when Peek(1) is '=':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PercentEqual);
|
||||
}
|
||||
case '%':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Percent);
|
||||
}
|
||||
case '&' when Peek(1) is '&':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.AmpersandAmpersand);
|
||||
}
|
||||
case '&':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Ampersand);
|
||||
}
|
||||
case '|' when Peek(1) is '|':
|
||||
{
|
||||
Consume();
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PipePipe);
|
||||
}
|
||||
case '|':
|
||||
{
|
||||
Consume();
|
||||
return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Pipe);
|
||||
}
|
||||
default:
|
||||
{
|
||||
if (char.IsLetter(c) || c == '_')
|
||||
{
|
||||
var buf = new StringBuilder();
|
||||
|
||||
while (TryPeek(out c) && (char.IsLetterOrDigit(c) || c == '_'))
|
||||
buf.Append(Consume());
|
||||
|
||||
var value = buf.ToString();
|
||||
|
||||
return value switch
|
||||
{
|
||||
"func" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Func),
|
||||
"struct" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Struct),
|
||||
"packed" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Packed),
|
||||
"enum" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Enum),
|
||||
"new" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.New),
|
||||
"match" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Match),
|
||||
"let" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Let),
|
||||
"if" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.If),
|
||||
"else" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Else),
|
||||
"while" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.While),
|
||||
"for" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.For),
|
||||
"in" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.In),
|
||||
"return" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Return),
|
||||
"module" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Module),
|
||||
"export" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Export),
|
||||
"extern" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Extern),
|
||||
"true" => new TokenBoolLiteral(line, startColumn, column - startColumn, true),
|
||||
"false" => new TokenBoolLiteral(line, startColumn, column - startColumn, false),
|
||||
_ => new TokenIdent(line, startColumn, column - startColumn, value)
|
||||
};
|
||||
}
|
||||
|
||||
throw new CompileException(Diagnostic.Error($"Unexpected character '{c}'").At(fileName, line, column, 1).Build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -493,6 +509,8 @@ public enum Symbol
|
||||
CloseCurly,
|
||||
OpenParen,
|
||||
CloseParen,
|
||||
OpenSquare,
|
||||
CloseSquare,
|
||||
Comma,
|
||||
Period,
|
||||
Colon,
|
||||
@@ -534,13 +552,19 @@ public enum Keyword
|
||||
Func,
|
||||
Struct,
|
||||
Packed,
|
||||
Enum,
|
||||
New,
|
||||
Match,
|
||||
Let,
|
||||
If,
|
||||
Else,
|
||||
While,
|
||||
For,
|
||||
In,
|
||||
Return,
|
||||
Module,
|
||||
Export,
|
||||
Extern,
|
||||
}
|
||||
|
||||
public class TokenKeyword(int line, int column, int length, Keyword keyword) : Token(line, column, length)
|
||||
@@ -558,6 +582,8 @@ public static class TokenExtensions
|
||||
Symbol.CloseCurly => "}",
|
||||
Symbol.OpenParen => "(",
|
||||
Symbol.CloseParen => ")",
|
||||
Symbol.OpenSquare => "[",
|
||||
Symbol.CloseSquare => "]",
|
||||
Symbol.Comma => ",",
|
||||
Symbol.Period => ".",
|
||||
Symbol.Colon => ":",
|
||||
@@ -598,13 +624,19 @@ public static class TokenExtensions
|
||||
Keyword.Func => "func",
|
||||
Keyword.Struct => "struct",
|
||||
Keyword.Packed => "packed",
|
||||
Keyword.Enum => "enum",
|
||||
Keyword.New => "new",
|
||||
Keyword.Match => "enum",
|
||||
Keyword.Let => "let",
|
||||
Keyword.If => "if",
|
||||
Keyword.Else => "else",
|
||||
Keyword.While => "while",
|
||||
Keyword.For => "for",
|
||||
Keyword.In => "in",
|
||||
Keyword.Return => "return",
|
||||
Keyword.Module => "module",
|
||||
Keyword.Export => "export",
|
||||
Keyword.Extern => "extern",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(symbol), symbol, null)
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
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 @@
|
||||
pushd math
|
||||
|
||||
dotnet run --project ../../compiler math.nub --type=lib
|
||||
|
||||
popd
|
||||
|
||||
pushd program
|
||||
|
||||
dotnet run --project ../../compiler main.nub ../math/.build/out.nublib
|
||||
|
||||
popd
|
||||
10
examples/core/print.nub
Normal file
10
examples/core/print.nub
Normal file
@@ -0,0 +1,10 @@
|
||||
module core
|
||||
|
||||
export func print(text: string) {
|
||||
sys::write(0, text.ptr, text.length)
|
||||
}
|
||||
|
||||
export func println(text: string) {
|
||||
print(text)
|
||||
print("\n")
|
||||
}
|
||||
5
examples/core/sys.nub
Normal file
5
examples/core/sys.nub
Normal file
@@ -0,0 +1,5 @@
|
||||
module sys
|
||||
|
||||
export extern func read(fd: u32, buf: ^char, count: u64): i64
|
||||
export extern func write(fd: u32, buf: ^char, count: u64): i64
|
||||
export extern func open(fileName: ^char, flags: i32, mode: u16): i64
|
||||
@@ -1,6 +0,0 @@
|
||||
module math
|
||||
|
||||
export func add(a: i32 b: i32): i32
|
||||
{
|
||||
return a + b
|
||||
}
|
||||
@@ -1,6 +1,32 @@
|
||||
module main
|
||||
|
||||
func main(): i32
|
||||
{
|
||||
return math::add(1 2)
|
||||
}
|
||||
struct Human {
|
||||
name: string
|
||||
age: i32
|
||||
}
|
||||
|
||||
enum Message {
|
||||
Quit
|
||||
Say: string
|
||||
}
|
||||
|
||||
func main(): i32 {
|
||||
|
||||
let x = new string("test".ptr) + " " + "uwu"
|
||||
core::println(x)
|
||||
|
||||
let messages: []Message = [new Message::Say("first"), new Message::Quit]
|
||||
|
||||
for message in messages {
|
||||
match message {
|
||||
Say msg {
|
||||
core::println(msg)
|
||||
}
|
||||
Quit {
|
||||
core::println("quit")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
module main
|
||||
|
||||
let global: i32
|
||||
|
||||
func main(): i32 {
|
||||
let x: i32 = 23
|
||||
x = 24
|
||||
|
||||
if !true {
|
||||
x = 49
|
||||
return x
|
||||
} else {
|
||||
x = 3
|
||||
}
|
||||
|
||||
let i: i32 = 0
|
||||
|
||||
x = 1 + 2 * 34
|
||||
while i < 10 {
|
||||
i = i + 1
|
||||
x = i
|
||||
}
|
||||
|
||||
let me: test::person = struct test::person { age = 21 name = "Oliver" }
|
||||
|
||||
x = test::do_something(me.name)
|
||||
test::do_something(me.name)
|
||||
|
||||
main::global = 123
|
||||
|
||||
return main::global
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
module test
|
||||
|
||||
export packed struct person {
|
||||
age: i32
|
||||
name: string
|
||||
}
|
||||
|
||||
export func do_something(name: string): i32 {
|
||||
return 3
|
||||
}
|
||||
Reference in New Issue
Block a user