Files
ziran/tests/spec/compiler_declaration_test.zi
T
waozi 7910e60542 Splice compile-time source into a module with #insert
`#insert NAME;` at file scope splices the text of a compile-time string
constant into the module where it stands: a literal, a #string body or
the result of `#run` on a pure procedure. The text is checked like the
rest of the file and shares its scope and #scope_file privacy, so a
compile-time procedure can write declarations generics cannot express.

Inserts are evaluated after discovery, under the #run rules and budget,
and their declarations are discovered before the file is parsed. Code
anywhere in the module can use them, including #if conditions and #run
calls above the #insert. The parser reads each insert as an in-memory
load frame. Every line of it keeps the #insert's line, so diagnostics
name the insertion site, and line numbers after the splice stay true.

A value that is not a compile-time string, #insert inside a procedure
body or an #if block, an insert in inserted text, and a misspelled
directive are rejected. The grammar lives in compiler_declaration.zi.
Saved IR holds only checked declarations, so no backend changes.

tests/insert_source_cases.zi builds a program whose Square, Cube and
helpers come from #insert. It runs from source and saved IR on C, Go,
the engine, native code and Wasm, with nine rejections.
2026-11-15 16:00:17 -03:00

709 lines
44 KiB
Ziran

#import "compiler_declaration"
SameParameters :: (source: string, expected: string, defaults: bool, using_values: bool,
flags: u64, has_defaults: bool) -> bool {
output: [256]u8
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
result := RewriteParameters(source, output[0:capacity], defaults, using_values, 128)
if result.error != .None || result.count != expected.count || output[capacity] != 0xa5 ||
TextView(output[0:capacity]) != expected[0:capacity] || result.using_parameters != flags ||
result.has_defaults != has_defaults { return false }
}
return true
}
SameUsingFilter :: (source: string, expected: string, rest: string) -> bool {
output: [256]u8
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
filter := UsingModifierClause(source, output[0:capacity], 128)
if filter.error != .None || !filter.present || filter.count != expected.count ||
source[filter.next:] != rest || output[capacity] != 0xa5 ||
TextView(output[0:capacity]) != expected[0:capacity] { return false }
}
return true
}
UsingModifiers :: () -> bool {
if !SameUsingFilter(", only(\"left\", \"right\") pair;", "O:left,right", "pair;") ||
!SameUsingFilter(", except ( \"left\", ) \tPair;", "E:left", "Pair;") ||
!SameUsingFilter(", map(\"first\" = \"left\", \"second\" = \"right\") pair;",
"M:first=left,second=right", "pair;") ||
!SameUsingFilter(", map ( \"alias\" = \"field\" )", "M:alias=field", "") { return false }
output: [256]u8
if UsingModifierClause("pair;", output[:], 128).present ||
UsingModifierClause("", output[:], 128).present ||
UsingModifierClause(", unknown(\"left\") pair;", output[:], 128).error != .UsingKind ||
UsingModifierClause(", only \"left\" pair;", output[:], 128).error != .UsingList ||
UsingModifierClause(", only() pair;", output[:], 128).error != .UsingList ||
UsingModifierClause(", only(\"left\" pair;", output[:], 128).error != .UsingList ||
UsingModifierClause(", only(left) pair;", output[:], 128).error != .UsingEntry ||
UsingModifierClause(", only(\"\") pair;", output[:], 128).error != .UsingEntry ||
UsingModifierClause(", only(\"unterminated", output[:], 128).error != .UsingEntry ||
UsingModifierClause(", only(\"left\") pair;", output[:], 4).error != .UsingEntry ||
UsingModifierClause(", map(\"alias\" \"field\") pair;", output[:], 128).error != .UsingMap ||
UsingModifierClause(", map(\"alias\" = \"\") pair;", output[:], 128).error != .UsingMap ||
UsingModifierClause(", map(\"a\" = \"field\") pair;", output[:], 5).error != .UsingMap { return false }
return true
}
ProcedureTypeParameters :: () -> bool {
output: [256]u8
source := " s32, value: *Node, Pair(s32, s64) "
expected := "arg0: s32, value: *Node, arg2: Pair(s32, s64)"
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
result := RewriteProcedureTypeParameters(source, output[0:capacity], 128)
if result.error != .None || result.parameters != 3 || result.count != expected.count ||
output[capacity] != 0xa5 || TextView(output[0:capacity]) != expected[0:capacity] { return false }
}
if RewriteProcedureTypeParameters("", output[:], 128).count != 0 ||
RewriteProcedureTypeParameters("value:", output[:], 128).error != .ProcedureTypeType ||
RewriteProcedureTypeParameters("a.b:s32", output[:], 128).error != .ProcedureTypeName ||
RewriteProcedureTypeParameters("long:s32", output[:], 4).error != .ProcedureTypeName ||
RewriteProcedureTypeParameters("s32,", output[:], 128).error != .ProcedureTypeType ||
RewriteProcedureTypeParameters("x:s32 = 2", output[:], 128).error != .ProcedureTypeDefault { return false }
source = "s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32"
result := RewriteProcedureTypeParameters(source, output[:], 128)
if result.error != .None || result.parameters != 16 ||
TextView(output[0:result.count]) != "arg0: s32, arg1: s32, arg2: s32, arg3: s32, arg4: s32, arg5: s32, arg6: s32, arg7: s32, arg8: s32, arg9: s32, arg10: s32, arg11: s32, arg12: s32, arg13: s32, arg14: s32, arg15: s32" {
return false
}
source = "s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32,s32"
if RewriteProcedureTypeParameters(source, output[:], 128).error != .ProcedureTypeCount { return false }
return true
}
Parameters :: () -> bool {
if !SameParameters("", "", true, true, 0, false) ||
!SameParameters(" \t", "", true, true, 0, false) ||
!SameParameters(" a:s32,b:s32 ", "a:s32, b:s32", true, false, 0, false) ||
!SameParameters("a:s32 = Call(1,2), text:string = \"a=b,c\", z := .{x=1,y=2}",
"a:s32, text:string, z :", true, false, 0, true) ||
!SameParameters("using a: *Node, using b: Pair(s32, s64), c:s32",
"a: *Node, b: Pair(s32, s64), c:s32", false, true, 3, false) ||
!SameParameters("using a: s32 = 2, b: string = \"using b: s32, =\"",
"a: s32, b: string", true, true, 1, true) ||
!SameParameters("a:s32 = Call(x == 2, y != 3), b:s32 = 4 >= 3",
"a:s32, b:s32", true, false, 0, true) { return false }
output: [1024]u8
if RewriteParameters("a:s32 = ", output[:], true, false, 128).error != .DefaultValue ||
RewriteParameters("using(a: s32)", output[:], false, true, 128).error != .UsingModifier ||
RewriteParameters("using a", output[:], false, true, 128).error != .UsingType ||
RewriteParameters("using a.b: Node", output[:], false, true, 128).error != .UsingName ||
RewriteParameters("using name: Node", output[:], false, true, 4).error != .UsingType { return false }
input: [1024]u8
count: s64 = 0
for parameter: 0..64 {
if parameter > 0 { input[count] = #char ","; count += 1 }
for byte: "using a:s32" { input[count] = byte; count += 1 }
result := RewriteParameters(TextView(input[0:count]), output[:], false, true, 128)
if parameter == 64 {
if result.error != .Parameters { return false }
} else {
if result.error != .None || result.parameters != parameter + 1 { return false }
if parameter == 63 && result.using_parameters != 0xffffffffffffffff { return false }
}
}
return true
}
Declarations :: () -> bool {
exported := ProgramExport("#program_export \"native_answer\" Answer :: () -> s32 { return 42 }", 128)
if exported.error != .None || exported.kind != 2 || exported.symbol != "native_answer" ||
exported.body != "Answer :: () -> s32 { return 42 }" { return false }
if ProgramExport("#program_export", 128).kind != 1 ||
ProgramExport("#program_export \"a\"", 2).kind != 1 ||
ProgramExport("#program_exported", 128).kind != 0 ||
ProgramExport("#program_export \"unterminated", 128).error != .ExportQuote ||
ProgramExport("#program_export \"aa\"", 2).error != .ExportQuote ||
ProgramExport("#program_export \"bad-name\"", 128).error != .ExportName ||
ProgramExport("#program_export \"\"", 128).error != .ExportName { return false }
imported := ImportDeclaration("#import \"std/text\";", 128, 1024)
if !imported.present || imported.error != .None || imported.named || imported.name != "text" ||
imported.target != "std/text" || imported.mode != .Module { return false }
imported = ImportDeclaration("#import \"kryon/host/desktop\";", 128, 1024)
if imported.error != .None || imported.named || imported.name != "desktop" ||
imported.target != "kryon/host/desktop" { return false }
imported = ImportDeclaration("using Library :: #import \"std/text\";", 128, 1024)
if imported.error != .None || !imported.named || !imported.using_import || imported.name != "Library" { return false }
imported = ImportDeclaration("Lib :: #import, file \"../lib/helper.zi\";", 128, 1024)
if imported.error != .None || !imported.named || imported.name != "Lib" || imported.target != "helper" ||
imported.path != "../lib/helper.zi" || imported.mode != .File { return false }
imported = ImportDeclaration("#import, dir \"../lib/helper\";", 128, 1024)
if imported.error != .None || imported.named || imported.name != "helper" || imported.target != "helper" ||
imported.path != "../lib/helper" || imported.mode != .Directory { return false }
if ImportDeclaration("Answer :: () { return 42 }", 128, 1024).present ||
ImportDeclaration("using #import \"lib\";", 128, 1024).present ||
ImportDeclaration("#import lib;", 128, 1024).error != .ImportQuote ||
ImportDeclaration("#import \"a>\";", 128, 1024).error != .ImportCharacter ||
ImportDeclaration("#import, bad \"lib\";", 128, 1024).error != .ImportMode ||
ImportDeclaration("#import, dir \"lib\"", 128, 1024).error != .ImportDirSyntax ||
ImportDeclaration("#import, file \"lib.zi\" extra;", 128, 1024).error != .ImportFileSyntax ||
ImportDeclaration("#import, dir \"/lib\";", 128, 1024).error != .ImportDirPath ||
ImportDeclaration("#import, dir \"lib/\";", 128, 1024).error != .ImportDirPath ||
ImportDeclaration("#import, dir \"bad-name\";", 128, 1024).error != .ImportDirName ||
ImportDeclaration("#import, file \"lib.c\";", 128, 1024).error != .ImportFilePath ||
ImportDeclaration("#import, file \"bad-name.zi\";", 128, 1024).error != .ImportFileName ||
ImportDeclaration("1Alias :: #import \"lib\";", 128, 1024).error != .ImportAlias ||
ImportDeclaration("#import \"bad-name\";", 128, 1024).error != .ImportTarget ||
ImportDeclaration("#import \"kryon//desktop\";", 128, 1024).error != .ImportTarget ||
ImportDeclaration("#import \"kryon/host/\";", 128, 1024).error != .ImportTarget ||
ImportDeclaration("#import \"\";", 128, 1024).error != .ImportTarget ||
ImportDeclaration("#import \"lib\";", 128, 3).error != .ImportQuote { return false }
library := SystemLibrary("lib :: #system_library \"go:net/http\";", 128, 1024)
if !library.present || library.error != .None || library.name != "lib" || library.target != "go:net/http" { return false }
if SystemLibrary("lib :: 42;", 128, 1024).present ||
SystemLibrary("lib :: #system_library \"\";", 128, 1024).error != .LibraryQuote ||
SystemLibrary("lib :: #system_library lib;", 128, 1024).error != .LibraryQuote ||
SystemLibrary("lib :: #system_library \"lib\"", 128, 1024).error != .LibraryEnd ||
SystemLibrary("lib :: #system_library \"bad\\name\";", 128, 1024).error != .LibraryCharacter ||
SystemLibrary("lib :: #system_library \"lib\";", 128, 3).error != .LibraryQuote { return false }
method := ForeignMethod("(*Client).Read", 128, 128)
if !method.valid || method.receiver != "*Client" || method.method != "Read" { return false }
if ForeignMethod("(Client).", 128, 128).valid ||
ForeignMethod("(Client).Read", 3, 128).valid ||
ForeignMethod("Client).Read", 128, 128).valid { return false }
for error: 1..23 { if ErrorText(cast(DeclarationError)error).count == 0 { return false } }
return ErrorText(.None) == ""
}
SameForeignTarget :: (source: string, library: string, expected: string) -> bool {
declaration := ParseForeign(source)
if !declaration.present || declaration.error != .None { return false }
output: [256]u8
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
target := ResolveForeignTarget(declaration, library, output[0:capacity])
if target.error != .None || target.count != expected.count || output[capacity] != 0xa5 ||
TextView(output[0:capacity]) != expected[0:capacity] { return false }
}
return true
}
ForeignDeclarations :: () -> bool {
declaration := ParseForeign("Read :: (reader: *Reader, output: []u8) -> Result #go_results #foreign lib \"(*Reader).Read\";")
if !declaration.present || declaration.error != .None || declaration.name != "Read" ||
declaration.library != "lib" || declaration.symbol != "(*Reader).Read" || !declaration.go_results ||
declaration.is_type || declaration.go_field || declaration.go_defer || declaration.go_variadic { return false }
declaration = ParseForeign("Reader :: #type #foreign lib;")
if !declaration.present || declaration.error != .None || !declaration.is_type ||
declaration.name != "Reader" || declaration.symbol != "Reader" { return false }
if !SameForeignTarget("Read :: () #foreign lib \"(*Reader).Read\";", "go:strings", "go:strings.(*Reader).Read") ||
!SameForeignTarget("Read :: () #go_results #foreign lib;", "go:io", "go:io.Read") ||
!SameForeignTarget("Read :: () #go_field #foreign lib;", "go:io", "go:io.Read") ||
!SameForeignTarget("Close :: () #go_defer #foreign lib;", "go:io", "go:io.Close") ||
!SameForeignTarget("Call :: () #go_variadic #foreign lib;", "go:fmt", "go:fmt.Call") ||
!SameForeignTarget("Reader :: #type #foreign lib;", "go:strings", "go:strings.Reader") ||
!SameForeignTarget("Call :: () #foreign lib;", "example.org/api", "example.org/api.Call") ||
!SameForeignTarget("Call :: () #foreign lib;", "m", "c.Call") ||
!SameForeignTarget("Call :: () #foreign lib;", "host_api", "") { return false }
if ParseForeign("").present || ParseForeign("text :: \"#foreign lib\";").present ||
ParseForeign("Call :: () { print(\"#foreign lib\") }").present ||
ParseForeign("Call :: () // #foreign lib;").present ||
ParseForeign("Call :: 42 #foreign lib;").present ||
ParseForeign("Call :: () #foreigner lib;").present ||
ParseForeign("Call :: () #foreign lib;", 4).present { return false }
// Quoted spellings, braces, and comments do not become attributes or bodies.
declaration = ParseForeign("Call :: (text: string = \"#go_results {\") #foreign lib;")
if declaration.error != .None || !declaration.present || declaration.go_results { return false }
if ParseForeign("Call :: () #go_results #go_results #foreign lib;").error != .ForeignResults ||
ParseForeign("Call :: #type #go_results #foreign lib;").error != .ForeignResults ||
ParseForeign("Call :: () #go_results #go_field #foreign lib;").error != .ForeignField ||
ParseForeign("Call :: () #go_field #go_defer #foreign lib;").error != .ForeignDefer ||
ParseForeign("Call :: () #go_variadic #go_variadic #foreign lib;").error != .ForeignVariadic ||
ParseForeign("Call :: () #foreign lib \"Print\" #go_variadic;").error != .ForeignVariadic ||
ParseForeign("Call :: () #go_field #go_variadic #foreign lib;").error != .ForeignVariadic ||
ParseForeign("Call :: #type Extra #foreign lib;").error != .ForeignType ||
ParseForeign("Call :: () { #foreign lib; }").error != .ForeignBody ||
ParseForeign("Call :: () #foreign ;").error != .ForeignLibrary ||
ParseForeign("C :: () #foreign library;", 4).error != .ForeignLibrary ||
ParseForeign("Call :: () #foreign lib \"unterminated;").error != .ForeignSymbol ||
ParseForeign("Call :: () #foreign lib").error != .ForeignEnd ||
ParseForeign("Call :: () #foreign lib; extra").error != .ForeignEnd { return false }
output: [256]u8
if ResolveForeignTarget(ParseForeign("Call :: () #foreign lib \"bad-name\";"), "go:io", output[:]).error != .ForeignSymbol ||
ResolveForeignTarget(ParseForeign("Call :: () #foreign lib \"Other\";"), "host_api", output[:]).error != .ForeignHostRename ||
ResolveForeignTarget(ParseForeign("Call :: () #go_results #foreign lib;"), "m", output[:]).error != .ForeignGoResults ||
ResolveForeignTarget(ParseForeign("Call :: () #go_field #foreign lib;"), "host_api", output[:]).error != .ForeignGoField ||
ResolveForeignTarget(ParseForeign("Call :: () #go_defer #foreign lib;"), "m", output[:]).error != .ForeignGoDefer ||
ResolveForeignTarget(ParseForeign("Call :: () #go_variadic #foreign lib;"), "example.org/lib", output[:]).error != .ForeignGoVariadic { return false }
if !ForeignVarargs("format: string, args: ..any") || !ForeignVarargs("..any") ||
!ForeignVarargs("a: s32, b: s32, c: s32, d: s32, e: s32, f: s32, g: s32, h: s32, i: s32, args: ..any") ||
ForeignVarargs("args: ..any, last: s32") || ForeignVarargs("text: string = \"..any\"") ||
ForeignVarargs("") { return false }
for error: 28..42 { if ErrorText(cast(DeclarationError)error).count == 0 { return false } }
return true
}
ResultSpellings :: () -> bool {
results := ParseResults("T, []U, Pair(T,U), *T", "U,T,Unused")
if results.error != .None || results.count != 4 || results.parameter_count != 2 ||
results.parameters[0] != "T" || results.parameters[1] != "U" ||
results.types[0] != "T" || results.types[3] != "*T" { return false }
output: [256]u8
record := "Results__T__a_U__Pair_T_U___pT"
parameters := "T,U"
body := "value_0: T\nvalue_1: []U\nvalue_2: Pair(T,U)\nvalue_3: *T\n"
for capacity: 0..body.count {
for index: 0..255 { output[index] = 0xa5 }
length := ResultsBody(results, output[0:capacity])
if length != body.count || TextView(output[0:capacity]) != body[0:capacity] ||
output[capacity] != 0xa5 { return false }
}
for capacity: 0..record.count {
for index: 0..255 { output[index] = 0xa5 }
length := ResultsRecord(results, output[0:capacity])
if length != record.count || TextView(output[0:capacity]) != record[0:capacity] ||
output[capacity] != 0xa5 { return false }
}
for capacity: 0..parameters.count {
for index: 0..255 { output[index] = 0xa5 }
length := ResultsParameters(results, output[0:capacity])
if length != parameters.count || TextView(output[0:capacity]) != parameters[0:capacity] ||
output[capacity] != 0xa5 { return false }
}
named := ParseResults(" (low: Pair(T,U), high: []T) ", "U,T")
if named.error != .None || named.count != 2 || named.parameter_count != 2 ||
named.types[0] != "Pair(T,U)" || named.types[1] != "[]T" ||
named.parameters[0] != "T" || named.parameters[1] != "U" { return false }
if ParseResults("", "").count != 0 || ParseResults("s32", "").count != 0 ||
ParseResults("Pair(T,U)", "T,U").count != 0 ||
ParseResults("(low: s32, s32)", "").error != .ResultName ||
ParseResults("(1: s32, high: s32)", "").error != .ResultName ||
ParseResults("s32, $T", "T").error != .ResultType ||
ParseResults("s32,", "").error != .ResultType ||
ParseResults(", s32", "").error != .ResultType ||
ParseResults("s32, a\0b", "").error != .ResultType { return false }
// Identical shapes keep the same template ordering across binder order.
other := ParseResults("T, []U, Pair(T,U), *T", "T,U")
if ResultsParameters(other, output[:]) != 3 || TextView(output[0:3]) != "T,U" { return false }
input: [128]u8
used: s64 = 0
for index: 0..16 {
if index > 0 { input[used] = #char ","; used += 1 }
for byte: "s32" { input[used] = byte; used += 1 }
many := ParseResults(TextView(input[0:used]), "")
if index == 16 {
if many.error != .ResultCount { return false }
} else if index > 0 && (many.error != .None || many.count != index + 1) { return false }
if index == 15 {
length := ResultsBody(many, output[:])
if length != 214 || TextView(output[length - 14:length]) != "value_15: s32\n" { return false }
}
}
return true
}
ResultStatements :: () -> bool {
output: [256]u8
statement := " return Call(1, 2), \"x,y\", .{left=1,right=2}; \t"
expected := "return Results__Pair.{Call(1, 2), \"x,y\", .{left=1,right=2}};"
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
rewritten := RewriteResultReturn(statement, "Results__Pair", 3, output[0:capacity])
if !rewritten.present || rewritten.error != .None || rewritten.values != 3 ||
rewritten.count != expected.count || output[capacity] != 0xa5 ||
TextView(output[0:capacity]) != expected[0:capacity] { return false }
}
if RewriteResultReturn("return F(1, 2);", "Pair", 2, output[:]).present ||
RewriteResultReturn("return \"x,y\";", "Pair", 2, output[:]).present ||
RewriteResultReturn("returning x, y", "Pair", 2, output[:]).present ||
RewriteResultReturn("", "Pair", 2, output[:]).present ||
RewriteResultReturn("return 1,2,3;", "Pair", 2, output[:]).error != .ReturnCount { return false }
binding := MultipleBinding(" left, _ , right := Call(1, \"a,b\"); \t")
if !binding.present || binding.count != 3 || !binding.inferred ||
binding.targets[0] != "left" || binding.targets[1] != "_" || binding.targets[2] != "right" ||
binding.value != "Call(1, \"a,b\")" { return false }
binding = MultipleBinding("x, y = ifx flag then 1 else 2;")
if !binding.present || binding.inferred || binding.count != 2 ||
binding.value != "ifx flag then 1 else 2" { return false }
if MultipleBinding("").present || MultipleBinding("a := Call()").present ||
MultipleBinding("a, b == Call()").present || MultipleBinding("a, b += Call()").present ||
MultipleBinding("a, b := ;").present || MultipleBinding("1a, b := Call()").present ||
MultipleBinding("a.field, b := Call()").present || MultipleBinding("a, b, := Call()").present ||
MultipleBinding("a, b := Call()", 1).present || MultipleBinding("aa, b := Call()", 16, 2).present { return false }
input: [128]u8
used: s64 = 0
for index: 0..16 {
if index > 0 { input[used] = #char ","; used += 1 }
input[used] = #char "a"; used += 1
at := used
for byte: " := F()" { input[at] = byte; at += 1 }
binding = MultipleBinding(TextView(input[0:at]))
if index == 16 {
if binding.present { return false }
} else if index > 0 && (!binding.present || binding.count != index + 1) { return false }
}
return true
}
ProcedureRewrites :: () -> bool {
if !DefaultScopeIndependent(".{left = 1, right = \"a,b\"}") ||
!DefaultScopeIndependent(".{left = .{nested = true}, right = null}") ||
!DefaultScopeIndependent("#char \"a\"") || !DefaultScopeIndependent("") ||
DefaultScopeIndependent(".{left = Constant}") || DefaultScopeIndependent("Call(1)") ||
DefaultScopeIndependent("#procedure_name()") || DefaultScopeIndependent("@") ||
DefaultScopeIndependent("\"long\"", 6) { return false }
source := "return #procedure_name ( ), \"#procedure_name()\", #procedure_name(); // #procedure_name(1)"
expected := "return \"Answer\", \"#procedure_name()\", \"Answer\"; // #procedure_name(1)"
output: [256]u8
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
result := RewriteProcedureName(source, "Answer", output[0:capacity])
if result.error != .None || !result.changed || result.count != expected.count ||
TextView(output[0:capacity]) != expected[0:capacity] || output[capacity] != 0xa5 { return false }
}
if RewriteProcedureName("\"#procedure_name(1)\"", "Answer", output[:]).changed ||
RewriteProcedureName("/* #procedure_name(1) /* nested */ */", "Answer", output[:]).changed ||
RewriteProcedureName("#procedure_name_extra()", "Answer", output[:]).changed ||
RewriteProcedureName("#procedure_name", "Answer", output[:]).error != .ProcedureNameArguments ||
RewriteProcedureName("#procedure_name(1)", "Answer", output[:]).error != .ProcedureNameArguments { return false }
names: [3]NameReplacement = .{.{"Twice", "first"}, .{"Other", "other"}, .{"Twice", "latest"}}
source = "Twice(Other()) + record . Twice + 1Twice + \"Twice\" /* Twice /* Other */ */ + Twice // Other"
expected = "latest(other()) + record . Twice + 1Twice + \"Twice\" /* Twice /* Other */ */ + latest // Other"
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5 }
result := RewriteLocalNames(source, names[:], output[0:capacity])
if result.error != .None || !result.changed || result.count != expected.count ||
TextView(output[0:capacity]) != expected[0:capacity] || output[capacity] != 0xa5 { return false }
}
result := RewriteLocalNames("Pair.{Twice = Twice()}, Call(Twice = Other())", names[:], output[:])
expected = "Pair.{Twice = latest()}, Call(Twice = other())"
if result.count != expected.count || TextView(output[0:result.count]) != expected { return false }
return !RewriteLocalNames("", names[:], output[:]).changed &&
!RewriteLocalNames("Other()", names[0:0], output[:]).changed
}
SymmetricOperators :: () -> bool {
source := "operator_multiply :: (a: * V, k: s32) -> * V #symmetric { return a; }"
expected := "operator_multiply :: (k: s32, a: *V) -> *V { return operator_multiply(a, k); }"
cleaned := "operator_multiply :: (a: * V, k: s32) -> * V { return a; }"
output: [256]u8
header: [256]u8
for capacity: 0..expected.count {
for index: 0..255 { output[index] = 0xa5; header[index] = 0xa5 }
result := RewriteSymmetric(source, header[0:capacity], output[0:capacity])
if result.error != .None || !result.present || !result.needed || result.count != expected.count ||
result.header_count != cleaned.count || TextView(output[0:capacity]) != expected[0:capacity] ||
output[capacity] != 0xa5 || header[capacity] != 0xa5 { return false }
copied := capacity
if copied > cleaned.count { copied = cleaned.count }
if TextView(header[0:copied]) != cleaned[0:copied] { return false }
}
if RewriteSymmetric("operator_add :: (a: * V, b: *V) -> V #symmetric { return a; }", header[:], output[:]).needed ||
RewriteSymmetric("operator_add :: (a: V, b: V) -> V #symmetric #symmetric { return a; }", header[:], output[:]).error != .SymmetricModifier ||
RewriteSymmetric("Twice :: (a: s32) -> s32 #symmetric { return a * 2; }", header[:], output[:]).error != .SymmetricParameters ||
RewriteSymmetric("operator_add :: (a: V, b: V, c: V) #symmetric { }", header[:], output[:]).error != .SymmetricParameters ||
RewriteSymmetric("operator_add :: (a, b: V) #symmetric { }", header[:], output[:]).error != .SymmetricParameters ||
RewriteSymmetric("operator_add :: (a: V, b: V) #symmetric { }", header[:], output[:], 5).error != .SymmetricParameters ||
RewriteSymmetric("operator_add :: (a: V, b: V) { print(\"#symmetric\") }", header[:], output[:]).present ||
RewriteSymmetric("Call :: (text: string = \"#symmetric\") { }", header[:], output[:]).present ||
RewriteSymmetric("", header[:], output[:]).present { return false }
return true
}
BuilderPieces :: () -> bool {
source := "BuilderPrint(*b, \"value=% %%\\n\", Call(1,2));"
expected: [3]string = .{"Append(*b, \"value=\");", "Append(*b, Call(1,2));", "Append(*b, \" %\\n\");"}
for capacity: 0..32 {
first: [64]u8
second: [64]u8
third: [64]u8
for index: 0..63 { first[index] = 0xa5; second[index] = 0xa5; third[index] = 0xa5 }
slots: [3]StatementOutput = .{.{first[0:capacity]}, .{second[0:capacity]}, .{third[0:capacity]}}
result := BuilderPrintPieces(source, slots[:])
if result.error != .None || result.statements != 3 ||
first[capacity] != 0xa5 || second[capacity] != 0xa5 || third[capacity] != 0xa5 { return false }
for index: 0..2 {
length := result.lengths[index]
if length != expected[index].count { return false }
copied := capacity
if copied > length { copied = length }
if TextView(slots[index].bytes[0:copied]) != expected[index][0:copied] { return false }
}
}
absent: []StatementOutput
result := BuilderPrintPieces(source, absent)
if result.error != .None || result.statements != 3 || result.lengths[1] != expected[1].count { return false }
if BuilderPrintPieces(source, absent, 2).error != .BuilderPieces ||
BuilderPrintPieces("BuilderPrint(*b, \"% %\", 1)", absent).error != .BuilderPercent ||
BuilderPrintPieces("BuilderPrint(*b, \"%\", 1, 2)", absent).error != .BuilderArguments ||
BuilderPrintPieces("BuilderPrint(*b)", absent).error != .BuilderFormat ||
BuilderPrintPieces("BuilderPrint(*b, variable)", absent).error != .BuilderFormat ||
BuilderPrintPieces("BuilderPrint(*b, \"\")", absent).statements != 0 ||
BuilderPrintPieces("BuilderPrinted(*b, \"%\", 1)", absent).statements != 0 ||
BuilderPrintPieces("BuilderPrint(*b, \"text\") extra", absent).statements != 0 { return false }
return true
}
#program_export
Answer :: () -> s32 {
if !Parameters() { return 1 }
if !Declarations() { return 2 }
if !UsingModifiers() { return 3 }
if !ForeignDeclarations() { return 4 }
if !ResultSpellings() { return 5 }
if !ResultStatements() { return 6 }
if !ProcedureRewrites() { return 7 }
if !SymmetricOperators() { return 8 }
if !BuilderPieces() { return 9 }
if !GoMethods() { return 10 }
if !ProcedureTypeParameters() { return 11 }
if !ModuleParameterGrammar() { return 12 }
if !InsertGrammar() { return 13 }
return 42
}
InsertGrammar :: () -> bool {
insert := InsertDeclaration("#insert TABLE; // generated", 128)
if !insert.present || insert.error != .None || insert.name != "TABLE" { return false }
if InsertDeclaration("#inserted TABLE;", 128).present ||
InsertDeclaration("TABLE :: 1;", 128).present ||
InsertDeclaration("#insert TABLE", 128).error != .InsertSyntax ||
InsertDeclaration("#insert 1TABLE;", 128).error != .InsertSyntax ||
InsertDeclaration("#insert Lib.TABLE;", 128).error != .InsertSyntax ||
InsertDeclaration("#insert TABLE; extra", 128).error != .InsertSyntax ||
InsertDeclaration("#insert TABLE;", 3).error != .InsertSyntax ||
InsertDeclaration("#insert ;", 128).error != .InsertSyntax { return false }
return true
}
ModuleParameterGrammar :: () -> bool {
imported := ImportDeclaration("Fonts :: #import \"fonts\"(STB = false, CACHE = 0x10);", 128, 1024)
if imported.error != .None || !imported.parameterized || imported.name != "Fonts" ||
imported.target != "fonts" || imported.parameters != "STB = false, CACHE = 0x10" { return false }
imported = ImportDeclaration("#import \"fonts\" (LABEL = \"a, b\")", 128, 1024)
if imported.error != .None || imported.parameters != "LABEL = \"a, b\"" { return false }
if ImportDeclaration("SOURCE :: \"Fonts :: #import \\\"fonts\\\"(A = 1);\";", 128, 1024).present ||
ImportDeclaration("#import \"fonts\";", 128, 1024).parameterized ||
ImportDeclaration("#import \"fonts\"();", 128, 1024).error != .ImportParameterList ||
ImportDeclaration("#import \"fonts\"(A = 1", 128, 1024).error != .ImportParameterList ||
ImportDeclaration("#import \"fonts\"(A = 1) extra;", 128, 1024).error != .ImportParameterList ||
ImportDeclaration("#import \"fonts\"(A = 1,);", 128, 1024).error != .ImportParameterList ||
ImportDeclaration("#import \"fonts\"(A);", 128, 1024).error != .ImportParameterList ||
ImportDeclaration("#import \"fonts\"(1A = 1);", 128, 1024).error != .ParameterName ||
ImportDeclaration("#import \"fonts\"(A = B);", 128, 1024).error != .ParameterValue ||
ImportDeclaration("#import \"fonts\"(A = null);", 128, 1024).error != .ParameterValue ||
ImportDeclaration("#import \"fonts\"(A = 1, A = 2);", 128, 1024).error != .ParameterDuplicate ||
ImportDeclaration("#import, file \"fonts.zi\"(A = 1);", 128, 1024).error != .ImportParameterMode ||
ImportDeclaration("#import, dir \"fonts\" (A = 1);", 128, 1024).error != .ImportParameterMode { return false }
entry := NextParameter("A := true, B: u8 = 255, C := \"x\"", 0, true, 128)
if entry.error != .None || entry.name != "A" || entry.type != "bool" || entry.value != "true" { return false }
entry = NextParameter("A := true, B: u8 = 255, C := \"x\"", entry.next, true, 128)
if entry.error != .None || entry.name != "B" || entry.type != "u8" || entry.value != "255" { return false }
entry = NextParameter("A := true, B: u8 = 255, C := \"x\"", entry.next, true, 128)
if entry.error != .None || entry.type != "string" || entry.next != -1 { return false }
if NextParameter("A := -2.5e3", 0, true, 128).type != "float64" ||
NextParameter("A := 7", 0, true, 128).type != "s64" ||
NextParameter("A: u8", 0, true, 128).error != .ParameterDefault ||
NextParameter("A", 0, true, 128).error != .ParameterDefault ||
NextParameter("A: Thing = 1", 0, true, 128).error != .ParameterType ||
NextParameter("A: u8 = 256", 0, true, 128).error != .ParameterFit ||
NextParameter("A: bool = 1", 0, true, 128).error != .ParameterFit ||
NextParameter("A := B", 0, true, 128).error != .ParameterValue ||
ParameterListError("A := 1, A := 2", true, 128) != .ParameterDuplicate { return false }
fits := string.["s8", "-128", "s8", "127", "u8", "255", "u64", "18446744073709551615",
"s64", "-9223372036854775808", "float32", "2", "string", "\"\\\"\"", "u8", "-0"]
for index: 0..fits.count / 2 - 1 { if !ParameterFits(fits[index * 2], fits[index * 2 + 1]) { return false } }
misfits := string.["s8", "-129", "s8", "128", "u8", "-1", "s64", "9223372036854775808",
"bool", "0", "string", "x", "u32", "1.5", "s32", "\"1\""]
for index: 0..misfits.count / 2 - 1 { if ParameterFits(misfits[index * 2], misfits[index * 2 + 1]) { return false } }
canonical: [32]u8
count := ParameterCanonical("0x1_0", canonical[:])
if TextView(canonical[0:count]) != "16" { return false }
count = ParameterCanonical("-0", canonical[:])
if TextView(canonical[0:count]) != "0" { return false }
count = ParameterCanonical("\"x\"", canonical[:])
if TextView(canonical[0:count]) != "\"x\"" || ParameterCanonical("\"x\"", canonical[0:2]) != -1 { return false }
directive := ModuleParametersPrefix("#!/usr/bin/env ziran\n// lead\n/* a /* nested */\n */\n#module_parameters(\n A := 1,\n B := false\n);\nRest :: 1\n", 128)
if !directive.present || directive.error != .None || directive.line != 5 ||
directive.list != "\n A := 1,\n B := false\n" { return false }
if ModuleParametersPrefix("Rest :: 1\n#module_parameters(A := 1)\n", 128).present ||
ModuleParametersPrefix("#module_parametersX(A := 1)\n", 128).present ||
ModuleParametersPrefix("#module_parameters A := 1\n", 128).error != .ParameterListSyntax ||
ModuleParametersPrefix("#module_parameters() \n", 128).error != .ParameterListSyntax ||
ModuleParametersPrefix("#module_parameters(A := 1) Rest :: 1\n", 128).error != .ParameterListSyntax ||
ModuleParametersPrefix("#module_parameters(A := 1); // note\n", 128).error != .None { return false }
return true
}
GoMethods :: () -> bool {
method := ParseGoMethod("Write :: (self: *Writer) -> Result #go_method \"Write\" #go_results { return .{} }")
if method.error != .None || method.name != "Write" || !method.results { return false }
method = ParseGoMethod("Write :: (self: Writer, default: string = \"#go_method\") #go_method \"Reset\" { }")
if method.error != .None || method.name != "Reset" || method.results { return false }
method = ParseGoMethod("Write :: (self: Writer) { print(\"#go_method\") }")
if method.error != .None || method.name != "" || method.results { return false }
if ParseGoMethod("Write :: (self: Writer) #go_method \"bad.name\" { }").error != .GoMethodQuote { return false }
if ParseGoMethod("Write :: (self: Writer) #go_method Missing { }").error != .GoMethodQuote { return false }
if ParseGoMethod("Write :: (self: Writer) #go_method \"X\" #go_method \"Y\" { }").error != .GoMethodDuplicate { return false }
if ParseGoMethod("Write :: (self: Writer) #go_method \"X\" #go_results #go_results { }").error != .GoMethodResults { return false }
if ParseGoMethod("Write :: (self: Writer) #go_results extra #go_method \"X\" { }").error != .GoMethodResults { return false }
if ParseGoMethod("Write :: (self: Writer) #go_method \"X\" #foreign native;").error != .GoMethodForeign { return false }
return true
}
#program_export
Fingerprint :: () -> s64 {
seed: u32 = 0x87654321
hash: u32 = 2166136261
alphabet := "using a:s32=1,(\"x=y,z\"){}[];<>\\\t#'./_\n"
input: [64]u8
output: [128]u8
foreign_input: [96]u8
return_input: [96]u8
header_output: [128]u8
symmetric_input: [192]u8
builder_input: [128]u8
replacements: [2]NameReplacement = .{.{"a", "renamed"}, .{"s32", "integer"}}
for sample: 0..255 {
seed = seed * cast(u32)1664525 + cast(u32)1013904223
count := cast(s64)(seed % cast(u32)64)
for index: 0..count - 1 {
seed = seed * cast(u32)1664525 + cast(u32)1013904223
input[index] = alphabet[cast(s64)(seed % cast(u32)alphabet.count)]
}
source := TextView(input[0:count])
for capacity: 0..8 {
rewritten := RewriteParameters(source, output[0:capacity], sample % 2 == 0, sample % 3 == 0, 8)
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.error
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.count
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.using_parameters
written := rewritten.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
filter := UsingModifierClause(source, output[0:capacity], 8)
hash = hash * cast(u32)16777619 ^ cast(u32)filter.error
hash = hash * cast(u32)16777619 ^ cast(u32)filter.present
hash = hash * cast(u32)16777619 ^ cast(u32)filter.count
hash = hash * cast(u32)16777619 ^ cast(u32)filter.next
written = filter.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
}
imported := ImportDeclaration(source, 8, 32)
hash = hash * cast(u32)16777619 ^ cast(u32)imported.error
for byte: imported.name { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
for byte: imported.target { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
exported := ProgramExport(source, 8)
hash = hash * cast(u32)16777619 ^ cast(u32)exported.error
hash = hash * cast(u32)16777619 ^ cast(u32)exported.kind
library := SystemLibrary(source, 8, 32)
hash = hash * cast(u32)16777619 ^ cast(u32)library.error
method := ForeignMethod(source, 8, 8)
hash = hash * cast(u32)16777619 ^ cast(u32)method.valid
used: s64 = 0
for byte: "F :: () " { foreign_input[used] = byte; used += 1 }
for byte: source { foreign_input[used] = byte; used += 1 }
for byte: " #foreign lib;" { foreign_input[used] = byte; used += 1 }
foreign_source := TextView(foreign_input[0:used])
foreign := ParseForeign(foreign_source, 8)
hash = hash * cast(u32)16777619 ^ cast(u32)foreign.error
hash = hash * cast(u32)16777619 ^ cast(u32)foreign.present
for byte: foreign.library { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
for byte: foreign.symbol { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
for capacity: 0..8 {
target := ResolveForeignTarget(foreign, "go:fmt", output[0:capacity], 8)
hash = hash * cast(u32)16777619 ^ cast(u32)target.error
hash = hash * cast(u32)16777619 ^ cast(u32)target.count
written := target.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
}
results := ParseResults(source, "a,s32,z")
hash = hash * cast(u32)16777619 ^ cast(u32)results.error
hash = hash * cast(u32)16777619 ^ cast(u32)results.count
hash = hash * cast(u32)16777619 ^ cast(u32)results.parameter_count
for index: 0..results.count - 1 {
for byte: results.types[index] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
}
binding := MultipleBinding(source, 16, 8)
hash = hash * cast(u32)16777619 ^ cast(u32)binding.present
hash = hash * cast(u32)16777619 ^ cast(u32)binding.count
hash = hash * cast(u32)16777619 ^ cast(u32)binding.inferred
for byte: binding.value { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
used = 0
for byte: "return " { return_input[used] = byte; used += 1 }
for byte: source { return_input[used] = byte; used += 1 }
return_source := TextView(return_input[0:used])
used = 0
for byte: "operator_add :: (" { symmetric_input[used] = byte; used += 1 }
for byte: source { symmetric_input[used] = byte; used += 1 }
for byte: ") -> s32 #symmetric { }" { symmetric_input[used] = byte; used += 1 }
symmetric_source := TextView(symmetric_input[0:used])
used = 0
for byte: "BuilderPrint(*b, " { builder_input[used] = byte; used += 1 }
for byte: source { builder_input[used] = byte; used += 1 }
builder_input[used] = #char ")"; used += 1
builder_source := TextView(builder_input[0:used])
hash = hash * cast(u32)16777619 ^ cast(u32)DefaultScopeIndependent(source, 8)
for capacity: 0..8 {
length := ResultsRecord(results, output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)length
written := length
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
renamed := RewriteLocalNames(source, replacements[:], output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)renamed.changed
hash = hash * cast(u32)16777619 ^ cast(u32)renamed.count
written = renamed.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
named := RewriteProcedureName(source, "Answer", output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)named.error
hash = hash * cast(u32)16777619 ^ cast(u32)named.changed
hash = hash * cast(u32)16777619 ^ cast(u32)named.count
written = named.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
wrapper := RewriteSymmetric(symmetric_source, header_output[0:capacity], output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)wrapper.error
hash = hash * cast(u32)16777619 ^ cast(u32)wrapper.present
hash = hash * cast(u32)16777619 ^ cast(u32)wrapper.needed
hash = hash * cast(u32)16777619 ^ cast(u32)wrapper.count
hash = hash * cast(u32)16777619 ^ cast(u32)wrapper.header_count
written = wrapper.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
written = wrapper.header_count
if written > capacity { written = capacity }
for byte: header_output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
slots: [1]StatementOutput = .{.{output[0:capacity]}}
printed := BuilderPrintPieces(builder_source, slots[:])
hash = hash * cast(u32)16777619 ^ cast(u32)printed.error
hash = hash * cast(u32)16777619 ^ cast(u32)printed.statements
for index: 0..printed.statements - 1 {
hash = hash * cast(u32)16777619 ^ cast(u32)printed.lengths[index]
}
if printed.statements > 0 {
written = printed.lengths[0]
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
}
length = ResultsParameters(results, output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)length
written = length
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
length = ResultsBody(results, output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)length
written = length
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
rewritten := RewriteResultReturn(return_source, "Pair", 2, output[0:capacity])
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.error
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.present
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.values
hash = hash * cast(u32)16777619 ^ cast(u32)rewritten.count
written = rewritten.count
if written > capacity { written = capacity }
for byte: output[0:written] { hash = hash * cast(u32)16777619 ^ cast(u32)byte }
}
}
return cast(s64)hash
}
Run :: () { print("% %\n", Answer(), Fingerprint()) }