`#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.
1415 lines
62 KiB
Ziran
1415 lines
62 KiB
Ziran
// Declaration syntax. Returned text borrows source and output storage belongs
|
|
// to the caller; IR construction and source diagnostics stay at the boundary.
|
|
Text :: #import "compiler_text";
|
|
Source :: #import "compiler_source";
|
|
Scan :: #import "compiler_scan";
|
|
|
|
DeclarationError :: enum s32 {
|
|
None; ExportQuote; ExportName; Parameters; DefaultValue;
|
|
UsingModifier; UsingType; UsingName; ImportQuote; ImportCharacter;
|
|
ImportMode; ImportDirSyntax; ImportDirPath; ImportDirName;
|
|
ImportFileSyntax; ImportFilePath; ImportFileName; ImportAlias; ImportAliasLimit;
|
|
ImportTarget; ImportPackage; ImportUsing;
|
|
LibraryQuote; LibraryEnd; LibraryCharacter;
|
|
UsingKind; UsingList; UsingEntry; UsingMap;
|
|
ForeignResults; ForeignField; ForeignDefer; ForeignVariadic; ForeignReads;
|
|
ForeignType; ForeignBody; ForeignLibrary; ForeignSymbol; ForeignEnd;
|
|
ForeignHostRename; ForeignGoResults; ForeignGoField;
|
|
ForeignGoDefer; ForeignGoVariadic;
|
|
ResultCount; ResultName; ResultType; ResultParameters; ReturnCount;
|
|
SymmetricParameters; SymmetricModifier; ProcedureNameArguments;
|
|
BuilderFormat; BuilderPercent; BuilderArguments; BuilderPieces; BuilderArgumentCount;
|
|
GoMethodQuote; GoMethodDuplicate; GoMethodResults; GoMethodForeign;
|
|
ProcedureTypeCount; ProcedureTypeName; ProcedureTypeType; ProcedureTypeDefault;
|
|
ImportParameterList; ImportParameterMode; ParameterListSyntax; ParameterName;
|
|
ParameterValue; ParameterDuplicate; ParameterType; ParameterDefault; ParameterFit;
|
|
InsertSyntax;
|
|
}
|
|
GoMethodDeclaration :: struct {
|
|
error: DeclarationError
|
|
name: string
|
|
results: bool
|
|
}
|
|
ExportDirective :: struct { error: DeclarationError; kind: s32; symbol: string; body: string }
|
|
ParameterRewrite :: struct {
|
|
error: DeclarationError
|
|
count: s64
|
|
parameters: s32
|
|
has_defaults: bool
|
|
using_parameters: u64
|
|
}
|
|
ImportMode :: enum s32 { Module; File; Directory }
|
|
ModuleImport :: struct {
|
|
error: DeclarationError
|
|
present: bool
|
|
named: bool
|
|
using_import: bool
|
|
mode: ImportMode
|
|
name: string
|
|
target: string
|
|
path: string
|
|
detail: string
|
|
// `#import "module"(NAME = value, ...)`: the text between the parentheses.
|
|
parameterized: bool
|
|
parameters: string
|
|
}
|
|
// One entry of a module parameter list: `NAME = value` in an import's list,
|
|
// or `NAME := value` / `NAME: Type = value` in `#module_parameters`. TYPE is
|
|
// the declared or inferred type of a declaration and empty for an import.
|
|
ParameterEntry :: struct {
|
|
error: DeclarationError
|
|
present: bool
|
|
name: string
|
|
type: string
|
|
value: string
|
|
next: s64
|
|
}
|
|
// `#module_parameters(...)` as the first declaration of a source file: LIST
|
|
// is the text between the parentheses and LINE the directive's line.
|
|
ModuleParameterDirective :: struct { error: DeclarationError; present: bool; list: string; line: s64 }
|
|
// `#insert NAME;`: NAME is a constant whose compile-time string is source.
|
|
InsertDirective :: struct { error: DeclarationError; present: bool; name: string }
|
|
LibraryDeclaration :: struct { error: DeclarationError; present: bool; name: string; target: string }
|
|
MethodSymbol :: struct { valid: bool; receiver: string; method: string }
|
|
UsingFilter :: struct { error: DeclarationError; present: bool; count: s64; next: s64 }
|
|
ForeignDeclaration :: struct {
|
|
error: DeclarationError
|
|
present: bool
|
|
name: string
|
|
library: string
|
|
symbol: string
|
|
is_type: bool
|
|
go_results: bool
|
|
go_field: bool
|
|
go_defer: bool
|
|
go_variadic: bool
|
|
// The procedure only reads its string and byte arguments during the call.
|
|
reads: bool
|
|
}
|
|
ForeignTarget :: struct { error: DeclarationError; count: s64 }
|
|
ResultDeclaration :: struct {
|
|
error: DeclarationError
|
|
count: s32
|
|
types: [16]string
|
|
parameter_count: s32
|
|
parameters: [64]string
|
|
}
|
|
ResultReturn :: struct { error: DeclarationError; present: bool; values: s32; count: s64 }
|
|
ResultBinding :: struct {
|
|
present: bool
|
|
count: s32
|
|
inferred: bool
|
|
targets: [16]string
|
|
value: string
|
|
}
|
|
SymmetricRewrite :: struct {
|
|
error: DeclarationError
|
|
present: bool
|
|
needed: bool
|
|
header_count: s64
|
|
count: s64
|
|
}
|
|
TextRewrite :: struct { error: DeclarationError; changed: bool; count: s64 }
|
|
NameReplacement :: struct { source: string; target: string }
|
|
PrintRewrite :: struct { error: DeclarationError; statements: s32; lengths: [64]s64 }
|
|
StatementOutput :: struct { bytes: []u8 }
|
|
|
|
#scope_file
|
|
Find :: (source: string, needle: string) -> s64 {
|
|
for at: 0..source.count {
|
|
if needle.count <= source.count - at && source[at:at + needle.count] == needle { return at }
|
|
}
|
|
return -1
|
|
}
|
|
Trim :: (source: string) -> string {
|
|
range := Text.TrimRange(source)
|
|
return source[range.begin:range.end]
|
|
}
|
|
Put :: (output: []u8, used: *s64, source: string) {
|
|
for byte: source {
|
|
if <<used < output.count { output[<<used] = byte }
|
|
<<used += 1
|
|
}
|
|
}
|
|
QuotedText :: struct { valid: bool; value: string; end: s64 }
|
|
Byte :: (source: string, at: s64) -> u8 {
|
|
if at < 0 || at >= source.count { return 0 }
|
|
return source[at]
|
|
}
|
|
// The index after the quoted literal that starts at AT, past escapes.
|
|
AfterQuoted :: (source: string, at: s64) -> s64 {
|
|
quote := source[at]
|
|
at += 1
|
|
while at < source.count {
|
|
byte := source[at]
|
|
at += 1
|
|
if byte == quote { return at }
|
|
if byte == #char "\\" && at < source.count { at += 1 }
|
|
}
|
|
return source.count + 1
|
|
}
|
|
Digits :: (source: string, at: s64) -> s64 {
|
|
while at < source.count && source[at] >= #char "0" && source[at] <= #char "9" { at += 1 }
|
|
return at
|
|
}
|
|
// DIGITS.DIGITS with an optional exponent, as in 1.5 or 2.0e-3.
|
|
FloatLiteral :: (source: string) -> bool {
|
|
whole := Digits(source, 0)
|
|
if whole == 0 || Byte(source, whole) != #char "." { return false }
|
|
fraction := Digits(source, whole + 1)
|
|
if fraction == whole + 1 { return false }
|
|
if fraction == source.count { return true }
|
|
if source[fraction] != #char "e" && source[fraction] != #char "E" { return false }
|
|
at := fraction + 1
|
|
if Byte(source, at) == #char "+" || Byte(source, at) == #char "-" { at += 1 }
|
|
exponent := Digits(source, at)
|
|
return exponent > at && exponent == source.count
|
|
}
|
|
// The width of integer type NAME, or 0 for any other name.
|
|
IntegerBits :: (name: string) -> s64 {
|
|
widths := string.["s8", "u8", "s16", "u16", "s32", "u32", "s64", "u64"]
|
|
bits := s64.[8, 8, 16, 16, 32, 32, 64, 64]
|
|
for index: 0..widths.count - 1 { if name == widths[index] { return bits[index] } }
|
|
return 0
|
|
}
|
|
Quoted :: (source: string, limit: s64) -> QuotedText {
|
|
begin := Find(source, "\"")
|
|
if begin < 0 { return .{} }
|
|
end := Find(source[begin + 1:], "\"")
|
|
if end < 0 || end >= limit { return .{} }
|
|
end += begin + 1
|
|
return .{true, source[begin + 1:end], end + 1}
|
|
}
|
|
SymbolBeforeColons :: (source: string, limit: s64) -> string {
|
|
colons := Find(source, "::")
|
|
if colons < 0 { return "" }
|
|
begin := Text.SkipSpace(source, 0, true)
|
|
end := begin
|
|
while end < colons && Text.IdentifierByte(source[end]) { end += 1 }
|
|
if end == begin || end - begin >= limit || Text.SkipSpace(source, end, true) != colons { return "" }
|
|
return source[begin:end]
|
|
}
|
|
Basename :: (source: string) -> string {
|
|
begin: s64 = 0
|
|
for at: 0..source.count - 1 { if source[at] == #char "/" { begin = at + 1 } }
|
|
return source[begin:]
|
|
}
|
|
|
|
#scope_export
|
|
ErrorText :: (error: DeclarationError) -> string {
|
|
if error == .ExportQuote { return "#program_export requires a valid quoted symbol" }
|
|
if error == .ExportName { return "#program_export symbol must be an identifier" }
|
|
if error == .Parameters { return "too many procedure parameters" }
|
|
if error == .DefaultValue { return "default parameter needs a value" }
|
|
if error == .ProcedureTypeCount { return "invalid procedure type parameters" }
|
|
if error == .ProcedureTypeName { return "procedure type parameter needs a name" }
|
|
if error == .ProcedureTypeType { return "procedure type parameter needs a type" }
|
|
if error == .ProcedureTypeDefault { return "defaults on procedure type parameters are not supported" }
|
|
if error == .UsingModifier { return "using parameter modifiers are not supported" }
|
|
if error == .UsingType { return "using parameter needs name: Type" }
|
|
if error == .UsingName { return "using parameter needs a plain name" }
|
|
if error == .ImportQuote { return "Jai #import requires a quoted module or file name" }
|
|
if error == .ImportCharacter { return "#import target contains a character that cannot appear in an include path" }
|
|
if error == .ImportMode { return "unsupported #import mode" }
|
|
if error == .ImportDirSyntax { return "#import, dir requires a quoted path and ';'" }
|
|
if error == .ImportDirPath { return "#import, dir requires a relative directory path" }
|
|
if error == .ImportDirName { return "#import, dir path needs an identifier directory name" }
|
|
if error == .ImportFileSyntax { return "#import, file requires a quoted path and ';'" }
|
|
if error == .ImportFilePath { return "#import, file requires a relative .zi path" }
|
|
if error == .ImportFileName { return "#import, file path needs an identifier filename" }
|
|
if error == .ImportAlias { return "import alias must start with a letter or underscore" }
|
|
if error == .ImportAliasLimit { return "import name exceeds the 127-byte limit; give it an explicit alias" }
|
|
if error == .ImportTarget { return "Jai #import requires a module identifier or PACKAGE/export/path with identifier segments; use #import, file for paths" }
|
|
if error == .ImportPackage { return "a package import uses identifier path segments, as in #import \"PACKAGE/export/path\"" }
|
|
if error == .ImportUsing { return "using #import requires a named module alias" }
|
|
if error == .ImportParameterList { return "an import's module parameters are a list (NAME = value, ...) before the closing ';'" }
|
|
if error == .ImportParameterMode { return "module parameters need a quoted module import; #import, file and #import, dir take none" }
|
|
if error == .ParameterListSyntax { return "#module_parameters needs a parenthesized list, as in #module_parameters(NAME := value);" }
|
|
if error == .ParameterName { return "a module parameter name must be an identifier" }
|
|
if error == .ParameterValue { return "a module parameter value must be a literal: an integer, a float, a string, true or false" }
|
|
if error == .ParameterDuplicate { return "a module parameter list names the same parameter twice" }
|
|
if error == .ParameterType { return "a module parameter type must be bool, string, an integer type or a float type" }
|
|
if error == .ParameterDefault { return "a module parameter needs a default value: NAME := value or NAME: Type = value" }
|
|
if error == .ParameterFit { return "a module parameter's default value does not fit its declared type" }
|
|
if error == .InsertSyntax { return "#insert needs NAME; naming a compile-time string constant" }
|
|
if error == .LibraryQuote { return "#system_library requires a quoted library name" }
|
|
if error == .LibraryEnd { return "#system_library declaration must end with ';'" }
|
|
if error == .LibraryCharacter { return "#system_library name contains an invalid character" }
|
|
if error == .UsingKind { return "using modifier must be only, except, or map" }
|
|
if error == .UsingList { return "using modifier requires a parenthesized name list" }
|
|
if error == .UsingEntry { return "using modifier entries must be quoted names" }
|
|
if error == .UsingMap { return "using map entries need \"new\" = \"old\"" }
|
|
if error == .ForeignResults { return "#go_results requires one foreign procedure result record" }
|
|
if error == .ForeignField { return "#go_field requires one foreign field accessor without #go_results" }
|
|
if error == .ForeignDefer { return "#go_defer requires one foreign procedure without result or field attributes" }
|
|
if error == .ForeignVariadic { return "#go_variadic requires one foreign procedure with a final slice parameter" }
|
|
if error == .ForeignReads { return "#reads goes once before #foreign on a foreign procedure" }
|
|
if error == .ForeignType { return "foreign type requires Name :: #type #foreign library;" }
|
|
if error == .ForeignBody { return "#foreign procedure declarations cannot have a body" }
|
|
if error == .ForeignLibrary { return "#foreign requires a named #system_library" }
|
|
if error == .ForeignSymbol { return "#foreign alternate symbol must be an identifier or a Go method expression" }
|
|
if error == .ForeignEnd { return "#foreign declaration must end with ';'" }
|
|
if error == .ForeignHostRename { return "host capability cannot rename a #foreign symbol" }
|
|
if error == .ForeignGoResults { return "#go_results requires an explicit Go foreign target" }
|
|
if error == .ForeignGoField { return "#go_field requires an explicit Go foreign target" }
|
|
if error == .ForeignGoDefer { return "#go_defer requires an explicit Go foreign target" }
|
|
if error == .ForeignGoVariadic { return "#go_variadic requires an explicit Go foreign target" }
|
|
if error == .ResultCount { return "a procedure can have at most 16 results" }
|
|
if error == .ResultName { return "named results need name: Type for every result" }
|
|
if error == .ResultType { return "a result of a procedure with several results needs a concrete type" }
|
|
if error == .ResultParameters { return "multiple result type parameters exceed the size limit" }
|
|
if error == .ReturnCount { return "return value count does not match the procedure results" }
|
|
if error == .SymmetricParameters { return "#symmetric requires an operator procedure with two parameters" }
|
|
if error == .SymmetricModifier { return "duplicate #symmetric procedure modifier" }
|
|
if error == .ProcedureNameArguments { return "#procedure_name() requires empty parentheses" }
|
|
if error == .BuilderFormat { return "BuilderPrint needs a builder and a literal format" }
|
|
if error == .BuilderPercent { return "BuilderPrint format has more % than arguments" }
|
|
if error == .BuilderArguments { return "BuilderPrint has more arguments than % in its format" }
|
|
if error == .BuilderPieces { return "BuilderPrint has too many pieces" }
|
|
if error == .BuilderArgumentCount { return "BuilderPrint has too many arguments" }
|
|
if error == .GoMethodQuote { return "#go_method requires a quoted method identifier" }
|
|
if error == .GoMethodDuplicate { return "duplicate #go_method procedure modifier" }
|
|
if error == .GoMethodResults { return "#go_results applies once to a #go_method procedure" }
|
|
if error == .GoMethodForeign { return "#go_method requires an ordinary procedure body" }
|
|
return ""
|
|
}
|
|
|
|
// Native interface methods retain the ordinary checked procedure body. Scan
|
|
// only its modifiers, so quoted defaults and body literals are never metadata.
|
|
ParseGoMethod :: (source: string, name_limit: s64 = 128) -> GoMethodDeclaration {
|
|
result: GoMethodDeclaration
|
|
opening := Find(source, "(")
|
|
if opening < 0 { return result }
|
|
closing := Source.ClosingParenthesis(source[opening:])
|
|
if closing < 0 { return result }
|
|
at := opening + closing + 1
|
|
result_count: s32 = 0
|
|
result_arguments := false
|
|
foreign := false
|
|
while at < source.count {
|
|
token := Scan.NextToken(source, at, 1, 1)
|
|
if token.kind == Scan.TokenKind.Eof { break }
|
|
spelling := source[token.begin:token.end]
|
|
if spelling == "{" || spelling == ";" { break }
|
|
at = token.end
|
|
if token.kind != Scan.TokenKind.Directive { continue }
|
|
if spelling == "#foreign" { foreign = true }
|
|
if spelling == "#go_results" {
|
|
result_count += 1
|
|
next := Scan.NextToken(source, at, 1, 1)
|
|
following := source[next.begin:next.end]
|
|
if next.kind != Scan.TokenKind.Directive && following != "{" {
|
|
result_arguments = true
|
|
}
|
|
}
|
|
if spelling != "#go_method" { continue }
|
|
if result.name.count != 0 {
|
|
result.error = .GoMethodDuplicate
|
|
return result
|
|
}
|
|
quoted_at := Text.SkipSpace(source, at, true)
|
|
quoted := UsingQuoted(source[quoted_at:], name_limit)
|
|
if !quoted.valid || !Source.IdentifierText(quoted.value, false) {
|
|
result.error = .GoMethodQuote
|
|
return result
|
|
}
|
|
result.name = quoted.value
|
|
at = quoted_at + quoted.end
|
|
next := Scan.NextToken(source, at, 1, 1)
|
|
following := source[next.begin:next.end]
|
|
if next.kind != Scan.TokenKind.Directive && following != "{" {
|
|
result.error = .GoMethodQuote
|
|
return result
|
|
}
|
|
}
|
|
if result.name.count == 0 { return result }
|
|
if foreign { result.error = .GoMethodForeign }
|
|
else if result_count > 1 || result_arguments { result.error = .GoMethodResults }
|
|
result.results = result_count != 0
|
|
return result
|
|
}
|
|
|
|
// A short output receives its prefix; count measures the complete filter.
|
|
// next advances past the clause and following whitespace, leaving the binding.
|
|
UsingModifierClause :: (source: string, output: []u8, name_limit: s64) -> UsingFilter {
|
|
result: UsingFilter
|
|
if source.count == 0 || source[0] != #char "," { return result }
|
|
result.present = true
|
|
at := Text.SkipSpace(source, 1, false)
|
|
mode := source[at:]
|
|
prefix := ""
|
|
if Source.StartsWord(mode, "only") { prefix = "O:"; at += 4 }
|
|
else if Source.StartsWord(mode, "except") { prefix = "E:"; at += 6 }
|
|
else if Source.StartsWord(mode, "map") { prefix = "M:"; at += 3 }
|
|
else { result.error = .UsingKind; return result }
|
|
at = Text.SkipSpace(source, at, false)
|
|
if at >= source.count || source[at] != #char "(" { result.error = .UsingList; return result }
|
|
at = Text.SkipSpace(source, at + 1, false)
|
|
Put(output, *result.count, prefix)
|
|
entries: s64 = 0
|
|
while at < source.count && source[at] != #char ")" {
|
|
quoted := UsingQuoted(source[at:], name_limit)
|
|
if !quoted.valid { result.error = .UsingEntry; return result }
|
|
name := quoted.value
|
|
at = Text.SkipSpace(source, at + quoted.end, false)
|
|
mapped := ""
|
|
if prefix == "M:" {
|
|
if at >= source.count || source[at] != #char "=" { result.error = .UsingMap; return result }
|
|
at = Text.SkipSpace(source, at + 1, false)
|
|
quoted = UsingQuoted(source[at:], name_limit)
|
|
if !quoted.valid { result.error = .UsingMap; return result }
|
|
mapped = quoted.value
|
|
at = Text.SkipSpace(source, at + quoted.end, false)
|
|
}
|
|
if entries > 0 { Put(output, *result.count, ",") }
|
|
Put(output, *result.count, name)
|
|
if prefix == "M:" { Put(output, *result.count, "="); Put(output, *result.count, mapped) }
|
|
entries += 1
|
|
if at >= source.count || source[at] != #char "," { break }
|
|
at = Text.SkipSpace(source, at + 1, false)
|
|
}
|
|
if entries == 0 || at >= source.count || source[at] != #char ")" {
|
|
result.error = .UsingList
|
|
return result
|
|
}
|
|
result.next = Text.SkipSpace(source, at + 1, false)
|
|
return result
|
|
}
|
|
|
|
#scope_file
|
|
UsingQuoted :: (source: string, limit: s64) -> QuotedText {
|
|
if source.count == 0 || source[0] != #char "\"" { return .{} }
|
|
at: s64 = 1
|
|
while at < source.count && source[at] != #char "\"" && source[at] != 0 { at += 1 }
|
|
if at == source.count || source[at] != #char "\"" || at == 1 || at - 1 >= limit { return .{} }
|
|
return .{true, source[1:at], at + 1}
|
|
}
|
|
#scope_export
|
|
|
|
ProgramExport :: (source: string, symbol_limit: s64) -> ExportDirective {
|
|
result: ExportDirective
|
|
if !Source.StartsWord(source, "#program_export") { return result }
|
|
at := Text.SkipSpace(source, 15, true)
|
|
if at < source.count && source[at] == #char "\"" {
|
|
quoted := Quoted(source[at:], symbol_limit)
|
|
if !quoted.valid { result.error = .ExportQuote; return result }
|
|
result.symbol = quoted.value
|
|
if !Source.IdentifierText(result.symbol, false) { result.error = .ExportName; return result }
|
|
at = Text.SkipSpace(source, at + quoted.end, true)
|
|
}
|
|
result.kind = 1
|
|
if at < source.count { result.kind = 2 }
|
|
result.body = source[at:]
|
|
return result
|
|
}
|
|
|
|
// A short output receives its prefix, while count measures the complete
|
|
// normalized text. Source and output must not overlap: comma spacing can grow.
|
|
RewriteParameters :: (source: string, output: []u8, strip_defaults: bool,
|
|
strip_using: bool, name_limit: s64) -> ParameterRewrite {
|
|
result: ParameterRewrite
|
|
if Text.SkipSpace(source, 0, true) == source.count { return result }
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
if result.parameters == 64 { result.error = .Parameters; return result }
|
|
range := Text.NextSourcePart(source, at)
|
|
part := Trim(source[range.begin:range.end])
|
|
if strip_defaults {
|
|
assignment := Text.TopLevelAssignment(part)
|
|
if assignment >= 0 {
|
|
if Text.SkipSpace(part, assignment + 1, true) == part.count {
|
|
result.error = .DefaultValue
|
|
return result
|
|
}
|
|
part = Trim(part[0:assignment])
|
|
result.has_defaults = true
|
|
}
|
|
}
|
|
if strip_using && Source.StartsWord(part, "using") {
|
|
if part.count <= 5 || !Text.SpaceByte(part[5]) { result.error = .UsingModifier; return result }
|
|
part = Trim(part[5:])
|
|
colon := Find(part, ":")
|
|
if colon <= 0 || colon >= name_limit { result.error = .UsingType; return result }
|
|
if !Source.IdentifierText(Trim(part[0:colon]), false) { result.error = .UsingName; return result }
|
|
result.using_parameters |= cast(u64)1 << cast(u64)result.parameters
|
|
}
|
|
if result.parameters > 0 { Put(output, *result.count, ", ") }
|
|
Put(output, *result.count, part)
|
|
result.parameters += 1
|
|
at = range.next
|
|
}
|
|
return result
|
|
}
|
|
|
|
// Normalize a callback signature without constructing declaration IR. Bounded
|
|
// outputs receive their prefix and count measures the complete result.
|
|
RewriteProcedureTypeParameters :: (source: string, output: []u8,
|
|
name_limit: s64) -> ParameterRewrite {
|
|
result: ParameterRewrite
|
|
if Text.SkipSpace(source, 0, true) == source.count { return result }
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
if result.parameters == 16 { result.error = .ProcedureTypeCount; return result }
|
|
range := Text.NextSourcePart(source, at)
|
|
part := Trim(source[range.begin:range.end])
|
|
if Text.TopLevelAssignment(part) >= 0 { result.error = .ProcedureTypeDefault; return result }
|
|
colon := Find(part, ":")
|
|
type := part
|
|
if result.parameters > 0 { Put(output, *result.count, ", ") }
|
|
if colon >= 0 {
|
|
name := Trim(part[0:colon])
|
|
if name.count >= name_limit || !Source.IdentifierText(name, false) {
|
|
result.error = .ProcedureTypeName
|
|
return result
|
|
}
|
|
Put(output, *result.count, name)
|
|
type = Trim(part[colon + 1:])
|
|
} else {
|
|
Put(output, *result.count, "arg")
|
|
digits: [2]u8
|
|
length: s64 = 0
|
|
if result.parameters >= 10 { digits[length] = #char "1"; length += 1 }
|
|
digits[length] = #char "0" + cast(u8)(result.parameters % 10)
|
|
length += 1
|
|
Put(output, *result.count, TextView(digits[0:length]))
|
|
}
|
|
if type.count == 0 || Find(type, ":") >= 0 { result.error = .ProcedureTypeType; return result }
|
|
Put(output, *result.count, ": ")
|
|
Put(output, *result.count, type)
|
|
result.parameters += 1
|
|
at = range.next
|
|
}
|
|
return result
|
|
}
|
|
|
|
ImportDeclaration :: (source: string, name_limit: s64, path_limit: s64) -> ModuleImport {
|
|
result: ModuleImport
|
|
// A string constant's text, such as module source in #string, is no import.
|
|
directive := Source.FindUnquoted(source, "#import", false)
|
|
if directive < 0 { return result }
|
|
body := source
|
|
result.using_import = Source.StartsWord(source, "using")
|
|
if result.using_import {
|
|
body = source[Text.SkipSpace(source, 5, true):]
|
|
if body.count == 0 || !Source.IdentifierText(body[0:1], false) { return result }
|
|
}
|
|
result.present = true
|
|
quoted := Quoted(source[directive:], path_limit)
|
|
if !quoted.valid { result.error = .ImportQuote; return result }
|
|
result.target = quoted.value
|
|
for byte: result.target {
|
|
if byte == #char "\"" || byte == #char ">" || byte < 0x20 {
|
|
result.error = .ImportCharacter
|
|
return result
|
|
}
|
|
}
|
|
mode := source[Text.SkipSpace(source, directive + 7, true):]
|
|
if mode.count > 0 && mode[0] == #char "," {
|
|
mode = mode[Text.SkipSpace(mode, 1, true):]
|
|
keyword: s64 = 0
|
|
if mode.count > 3 && mode[0:3] == "dir" && Text.SpaceByte(mode[3]) {
|
|
result.mode = .Directory
|
|
keyword = 3
|
|
} else if mode.count > 4 && mode[0:4] == "file" && Text.SpaceByte(mode[4]) {
|
|
result.mode = .File
|
|
keyword = 4
|
|
} else { result.error = .ImportMode; result.detail = mode; return result }
|
|
argument := mode[Text.SkipSpace(mode, keyword, true):]
|
|
path := Quoted(argument, path_limit)
|
|
if path.valid && argument.count > 0 && argument[0] == #char "\"" &&
|
|
Byte(argument, Text.SkipSpace(argument, path.end, true)) == #char "(" {
|
|
result.error = .ImportParameterMode
|
|
return result
|
|
}
|
|
if argument.count == 0 || argument[0] != #char "\"" || !path.valid ||
|
|
argument[Text.SkipSpace(argument, path.end, true):] != ";" {
|
|
result.error = .ImportFileSyntax
|
|
if result.mode == .Directory { result.error = .ImportDirSyntax }
|
|
return result
|
|
}
|
|
result.name = SymbolBeforeColons(source, name_limit)
|
|
result.named = result.name.count > 0
|
|
result.path = result.target
|
|
valid := result.path.count > 0 && result.path[0] != #char "/"
|
|
if result.mode == .Directory {
|
|
valid = valid && Find(result.path, "\\") < 0 && result.path[result.path.count - 1] != #char "/"
|
|
} else { valid = valid && result.path.count >= 4 && result.path[result.path.count - 3:] == ".zi" }
|
|
if !valid {
|
|
result.error = .ImportFilePath
|
|
if result.mode == .Directory { result.error = .ImportDirPath }
|
|
return result
|
|
}
|
|
stem := Basename(result.path)
|
|
if result.mode == .File { stem = stem[0:stem.count - 3] }
|
|
if stem.count >= name_limit || !Source.IdentifierText(stem, false) {
|
|
result.error = .ImportFileName
|
|
if result.mode == .Directory { result.error = .ImportDirName }
|
|
return result
|
|
}
|
|
if !result.named { result.name = stem }
|
|
result.target = stem
|
|
} else {
|
|
result.name = SymbolBeforeColons(body, name_limit)
|
|
result.named = result.name.count > 0
|
|
if !result.named {
|
|
result.name = Basename(result.target)
|
|
if result.name.count >= name_limit { result.error = .ImportAliasLimit; return result }
|
|
}
|
|
rest := source[directive + quoted.end:]
|
|
rest = rest[Text.SkipSpace(rest, 0, true):]
|
|
if rest.count > 0 && rest[0] == #char "(" {
|
|
close := Source.ClosingParenthesis(rest)
|
|
after := ""
|
|
if close >= 0 { after = Trim(rest[close + 1:]) }
|
|
if close < 0 || Trim(rest[1:close]).count == 0 || (after != "" && after != ";") {
|
|
result.error = .ImportParameterList
|
|
return result
|
|
}
|
|
result.parameterized = true
|
|
result.parameters = rest[1:close]
|
|
result.error = ParameterListError(result.parameters, false, name_limit)
|
|
if result.error != .None { return result }
|
|
}
|
|
}
|
|
if result.named && !Source.IdentifierText(result.name[0:1], false) { result.error = .ImportAlias; return result }
|
|
start: s64 = 0
|
|
while start <= result.target.count {
|
|
slash := Find(result.target[start:], "/")
|
|
finish := result.target.count
|
|
if slash >= 0 { finish = start + slash }
|
|
if !Source.IdentifierText(result.target[start:finish], false) {
|
|
result.error = .ImportTarget
|
|
return result
|
|
}
|
|
if slash < 0 { break }
|
|
start = finish + 1
|
|
}
|
|
if result.using_import && !result.named { result.error = .ImportUsing }
|
|
return result
|
|
}
|
|
|
|
// The literal class of VALUE: bool, string, s64 for an integer and float64
|
|
// for a float, or "" when VALUE is not a module parameter literal.
|
|
ParameterLiteralType :: (value: string) -> string {
|
|
if value == "true" || value == "false" { return "bool" }
|
|
if value.count >= 2 && value[0] == #char "\"" && AfterQuoted(value, 0) == value.count &&
|
|
value[value.count - 1] == #char "\"" { return "string" }
|
|
digits := value
|
|
if digits.count > 1 && digits[0] == #char "-" { digits = digits[1:] }
|
|
if Text.IntegerLiteral(digits).valid { return "s64" }
|
|
if FloatLiteral(digits) { return "float64" }
|
|
return ""
|
|
}
|
|
|
|
// Whether TYPE may be declared for a module parameter.
|
|
ParameterTypeName :: (type: string) -> bool {
|
|
return type == "bool" || type == "string" || type == "float32" || type == "float64" ||
|
|
IntegerBits(type) > 0
|
|
}
|
|
|
|
// Whether the literal VALUE is a value of parameter type TYPE; integers must
|
|
// fit the type's range.
|
|
ParameterFits :: (type: string, value: string) -> bool {
|
|
class := ParameterLiteralType(value)
|
|
if type == "bool" || type == "string" { return class == type }
|
|
if type == "float32" || type == "float64" { return class == "float64" || class == "s64" }
|
|
bits := IntegerBits(type)
|
|
if bits == 0 || class != "s64" { return false }
|
|
negative := value[0] == #char "-"
|
|
magnitude := Text.IntegerLiteral(ifx negative then value[1:] else value).value
|
|
if type[0] == #char "u" {
|
|
if negative { return magnitude == 0 }
|
|
return bits == 64 || magnitude < (cast(u64)1 << cast(u64)bits)
|
|
}
|
|
limit: u64 = cast(u64)1 << cast(u64)(bits - 1)
|
|
if negative { return magnitude <= limit }
|
|
return magnitude < limit
|
|
}
|
|
|
|
// VALUE as a parameter binding compares it: an integer in decimal with its
|
|
// sign, any other literal as written. Returns the bytes written to OUTPUT,
|
|
// or -1 when they do not fit.
|
|
ParameterCanonical :: (value: string, output: []u8) -> s64 {
|
|
used: s64 = 0
|
|
if ParameterLiteralType(value) != "s64" {
|
|
Put(output, *used, value)
|
|
return ifx used <= output.count then used else -1
|
|
}
|
|
negative := value[0] == #char "-"
|
|
magnitude := Text.IntegerLiteral(ifx negative then value[1:] else value).value
|
|
digits: [20]u8
|
|
count: s64 = 0
|
|
while true {
|
|
digits[count] = #char "0" + cast(u8)(magnitude % cast(u64)10)
|
|
count += 1
|
|
magnitude /= cast(u64)10
|
|
if magnitude == cast(u64)0 { break }
|
|
}
|
|
if negative && !(count == 1 && digits[0] == #char "0") { Put(output, *used, "-") }
|
|
while count > 0 {
|
|
count -= 1
|
|
if used < output.count { output[used] = digits[count] }
|
|
used += 1
|
|
}
|
|
return ifx used <= output.count then used else -1
|
|
}
|
|
|
|
// The entry of LIST that starts at AT. An import entry is `NAME = value`;
|
|
// a declaration entry is `NAME := value` or `NAME: Type = value`. NEXT is
|
|
// where the following entry starts, or -1 after the last one.
|
|
NextParameter :: (list: string, at: s64, declaration: bool, name_limit: s64) -> ParameterEntry {
|
|
result: ParameterEntry
|
|
if at < 0 || at > list.count { return result }
|
|
range := Text.NextSourcePart(list, at)
|
|
result.present = true
|
|
result.next = range.next
|
|
part := Trim(list[range.begin:range.end])
|
|
if part.count == 0 {
|
|
result.error = ifx declaration then DeclarationError.ParameterListSyntax else .ImportParameterList
|
|
return result
|
|
}
|
|
name_end: s64 = 0
|
|
while name_end < part.count && Text.IdentifierByte(part[name_end]) { name_end += 1 }
|
|
result.name = part[0:name_end]
|
|
if name_end >= name_limit || !Source.IdentifierText(result.name, false) {
|
|
result.error = .ParameterName
|
|
return result
|
|
}
|
|
rest := part[Text.SkipSpace(part, name_end, true):]
|
|
if !declaration {
|
|
if rest.count == 0 || rest[0] != #char "=" || Byte(rest, 1) == #char "=" {
|
|
result.error = ifx rest.count == 0 || rest[0] == #char "=" then DeclarationError.ImportParameterList else .ParameterName
|
|
return result
|
|
}
|
|
result.value = Trim(rest[1:])
|
|
if ParameterLiteralType(result.value) == "" { result.error = .ParameterValue }
|
|
return result
|
|
}
|
|
if rest.count == 0 || rest[0] != #char ":" {
|
|
result.error = ifx rest.count == 0 then DeclarationError.ParameterDefault else .ParameterName
|
|
return result
|
|
}
|
|
rest = rest[1:]
|
|
if rest.count > 0 && rest[0] == #char "=" {
|
|
result.value = Trim(rest[1:])
|
|
result.type = ParameterLiteralType(result.value)
|
|
if result.type == "" { result.error = .ParameterValue }
|
|
return result
|
|
}
|
|
assignment := Text.TopLevelAssignment(rest)
|
|
if assignment < 0 {
|
|
result.type = Trim(rest)
|
|
result.error = ifx ParameterTypeName(result.type) then DeclarationError.ParameterDefault else .ParameterType
|
|
return result
|
|
}
|
|
result.type = Trim(rest[0:assignment])
|
|
result.value = Trim(rest[assignment + 1:])
|
|
if !ParameterTypeName(result.type) { result.error = .ParameterType }
|
|
else if ParameterLiteralType(result.value) == "" { result.error = .ParameterValue }
|
|
else if !ParameterFits(result.type, result.value) { result.error = .ParameterFit }
|
|
return result
|
|
}
|
|
|
|
// The first error of LIST read as import or declaration entries, including
|
|
// a name given twice.
|
|
ParameterListError :: (list: string, declaration: bool, name_limit: s64) -> DeclarationError {
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
entry := NextParameter(list, at, declaration, name_limit)
|
|
if entry.error != .None { return entry.error }
|
|
earlier: s64 = 0
|
|
while earlier >= 0 && earlier < at {
|
|
previous := NextParameter(list, earlier, declaration, name_limit)
|
|
if previous.name == entry.name { return .ParameterDuplicate }
|
|
earlier = previous.next
|
|
}
|
|
at = entry.next
|
|
}
|
|
return .None
|
|
}
|
|
|
|
// `#insert NAME;` with an optional line comment after the ';'.
|
|
InsertDeclaration :: (source: string, name_limit: s64) -> InsertDirective {
|
|
result: InsertDirective
|
|
if !Source.StartsWord(source, "#insert") { return result }
|
|
result.present = true
|
|
at := Text.SkipSpace(source, 7, true)
|
|
end := at
|
|
while end < source.count && Text.IdentifierByte(source[end]) { end += 1 }
|
|
result.name = source[at:end]
|
|
rest := source[Text.SkipSpace(source, end, true):]
|
|
if result.name.count >= name_limit || !Source.IdentifierText(result.name, false) ||
|
|
rest.count == 0 || rest[0] != #char ";" {
|
|
result.error = .InsertSyntax
|
|
return result
|
|
}
|
|
rest = Trim(rest[1:])
|
|
if rest.count > 0 && !(rest.count >= 2 && rest[0:2] == "//") { result.error = .InsertSyntax }
|
|
return result
|
|
}
|
|
|
|
// `#module_parameters(...)` when it is the first declaration of SOURCE, after
|
|
// blank lines, comments and a `#!` line; absent otherwise.
|
|
ModuleParametersPrefix :: (source: string, name_limit: s64) -> ModuleParameterDirective {
|
|
result: ModuleParameterDirective
|
|
at: s64 = 0
|
|
line: s64 = 1
|
|
if source.count >= 2 && source[0:2] == "#!" {
|
|
while at < source.count && source[at] != #char "\n" { at += 1 }
|
|
}
|
|
while at < source.count {
|
|
byte := source[at]
|
|
if byte == #char "\n" { line += 1; at += 1 }
|
|
else if Text.SpaceByte(byte) { at += 1 }
|
|
else if byte == #char "/" && Byte(source, at + 1) == #char "/" {
|
|
while at < source.count && source[at] != #char "\n" { at += 1 }
|
|
} else if byte == #char "/" && Byte(source, at + 1) == #char "*" {
|
|
depth: s32 = 0
|
|
while at < source.count {
|
|
if source[at] == #char "/" && Byte(source, at + 1) == #char "*" { depth += 1; at += 2 }
|
|
else if source[at] == #char "*" && Byte(source, at + 1) == #char "/" {
|
|
depth -= 1
|
|
at += 2
|
|
if depth == 0 { break }
|
|
} else {
|
|
if source[at] == #char "\n" { line += 1 }
|
|
at += 1
|
|
}
|
|
}
|
|
} else { break }
|
|
}
|
|
directive := "#module_parameters"
|
|
if at + directive.count > source.count || source[at:at + directive.count] != directive ||
|
|
Text.IdentifierByte(Byte(source, at + directive.count)) { return result }
|
|
result.present = true
|
|
result.line = line
|
|
at = Text.SkipSpace(source, at + directive.count, true)
|
|
close := Source.ClosingParenthesis(source[at:])
|
|
if close < 0 { result.error = .ParameterListSyntax; return result }
|
|
result.list = source[at + 1:at + close]
|
|
after := Text.SkipSpace(source, at + close + 1, true)
|
|
if Byte(source, after) == #char ";" { after = Text.SkipSpace(source, after + 1, true) }
|
|
if after < source.count && source[after] != #char "\n" && source[after] != #char "\r" &&
|
|
!(source[after] == #char "/" && Byte(source, after + 1) == #char "/") {
|
|
result.error = .ParameterListSyntax
|
|
return result
|
|
}
|
|
if Trim(result.list).count == 0 { result.error = .ParameterListSyntax; return result }
|
|
result.error = ParameterListError(result.list, true, name_limit)
|
|
return result
|
|
}
|
|
|
|
SystemLibrary :: (source: string, name_limit: s64, path_limit: s64) -> LibraryDeclaration {
|
|
result: LibraryDeclaration
|
|
result.name = SymbolBeforeColons(source, name_limit)
|
|
if result.name.count == 0 { return result }
|
|
declaration := source[Text.SkipSpace(source, Find(source, "::") + 2, true):]
|
|
if !Source.StartsWord(declaration, "#system_library") { return result }
|
|
result.present = true
|
|
argument := declaration[Text.SkipSpace(declaration, 15, true):]
|
|
quoted := Quoted(argument, path_limit)
|
|
if argument.count == 0 || argument[0] != #char "\"" || !quoted.valid || quoted.value.count == 0 {
|
|
result.error = .LibraryQuote
|
|
return result
|
|
}
|
|
result.target = quoted.value
|
|
if argument[Text.SkipSpace(argument, quoted.end, true):] != ";" { result.error = .LibraryEnd; return result }
|
|
for byte: result.target {
|
|
if byte < 0x20 || byte == #char "\"" || byte == #char "\\" { result.error = .LibraryCharacter; return result }
|
|
}
|
|
return result
|
|
}
|
|
|
|
ForeignMethod :: (source: string, receiver_limit: s64, method_limit: s64) -> MethodSymbol {
|
|
result: MethodSymbol
|
|
dot := Find(source, ".")
|
|
if dot <= 0 { return result }
|
|
result.receiver = source[0:dot]
|
|
result.method = source[dot + 1:]
|
|
if source[0] == #char "(" {
|
|
if result.receiver.count < 3 || result.receiver[result.receiver.count - 1] != #char ")" { return result }
|
|
result.receiver = result.receiver[1:result.receiver.count - 1]
|
|
}
|
|
if result.receiver.count >= receiver_limit || result.method.count >= method_limit { return result }
|
|
name := result.receiver
|
|
if name.count > 0 && name[0] == #char "*" { name = name[1:] }
|
|
result.valid = Source.IdentifierText(name, false) && Source.IdentifierText(result.method, false)
|
|
return result
|
|
}
|
|
|
|
// Directives are tokens, so quoted defaults and alternate symbols cannot
|
|
// masquerade as modifiers. Every returned spelling borrows the bounded input.
|
|
ParseForeign :: (source: string, name_limit: s64 = 128) -> ForeignDeclaration {
|
|
result: ForeignDeclaration
|
|
result.name = SymbolBeforeColons(source, name_limit)
|
|
if result.name.count == 0 { return result }
|
|
declaration := source[Text.SkipSpace(source, Find(source, "::") + 2, true):]
|
|
attributes: [5]s32
|
|
after_foreign: [5]bool
|
|
directive: s64 = -1
|
|
body := false
|
|
at: s64 = 0
|
|
while at < declaration.count {
|
|
token := Scan.NextToken(declaration, at, 1, 1)
|
|
if token.kind == Scan.TokenKind.Eof { break }
|
|
spelling := declaration[token.begin:token.end]
|
|
if spelling == "/" && token.end < declaration.count && declaration[token.end] == #char "/" { break }
|
|
if spelling == "{" { body = true }
|
|
if token.kind == Scan.TokenKind.Directive {
|
|
if spelling == "#foreign" && directive < 0 { directive = token.begin }
|
|
attribute: s64 = -1
|
|
if spelling == "#go_results" { attribute = 0 }
|
|
if spelling == "#go_field" { attribute = 1 }
|
|
if spelling == "#go_defer" { attribute = 2 }
|
|
if spelling == "#go_variadic" { attribute = 3 }
|
|
if spelling == "#reads" { attribute = 4 }
|
|
if attribute >= 0 {
|
|
attributes[attribute] += 1
|
|
if directive >= 0 { after_foreign[attribute] = true }
|
|
}
|
|
}
|
|
at = token.end
|
|
}
|
|
if directive < 0 { return result }
|
|
result.present = true
|
|
result.is_type = Source.StartsWord(declaration, "#type")
|
|
result.go_results = attributes[0] > 0
|
|
result.go_field = attributes[1] > 0
|
|
result.go_defer = attributes[2] > 0
|
|
result.go_variadic = attributes[3] > 0
|
|
result.reads = attributes[4] > 0
|
|
if result.go_results && (result.is_type || attributes[0] > 1 || after_foreign[0]) {
|
|
result.error = .ForeignResults
|
|
return result
|
|
}
|
|
if result.go_field && (result.is_type || result.go_results || attributes[1] > 1 || after_foreign[1]) {
|
|
result.error = .ForeignField
|
|
return result
|
|
}
|
|
if result.go_defer && (result.is_type || result.go_results || result.go_field || attributes[2] > 1 || after_foreign[2]) {
|
|
result.error = .ForeignDefer
|
|
return result
|
|
}
|
|
if result.go_variadic && (result.is_type || result.go_field || attributes[3] > 1 || after_foreign[3]) {
|
|
result.error = .ForeignVariadic
|
|
return result
|
|
}
|
|
if result.reads && (result.is_type || attributes[4] > 1 || after_foreign[4]) {
|
|
result.error = .ForeignReads
|
|
return result
|
|
}
|
|
if result.is_type && Text.SkipSpace(declaration, 5, true) != directive {
|
|
result.error = .ForeignType
|
|
return result
|
|
}
|
|
if !result.is_type && (declaration.count == 0 || declaration[0] != #char "(") {
|
|
result.present = false
|
|
return result
|
|
}
|
|
if body { result.error = .ForeignBody; return result }
|
|
at = Text.SkipSpace(declaration, directive + 8, true)
|
|
begin := at
|
|
while at < declaration.count && Text.IdentifierByte(declaration[at]) { at += 1 }
|
|
result.library = declaration[begin:at]
|
|
if result.library.count >= name_limit || !Source.IdentifierText(result.library, false) {
|
|
result.error = .ForeignLibrary
|
|
return result
|
|
}
|
|
at = Text.SkipSpace(declaration, at, true)
|
|
result.symbol = result.name
|
|
if at < declaration.count && declaration[at] == #char "\"" {
|
|
quoted := UsingQuoted(declaration[at:], name_limit)
|
|
if !quoted.valid { result.error = .ForeignSymbol; return result }
|
|
result.symbol = quoted.value
|
|
at = Text.SkipSpace(declaration, at + quoted.end, true)
|
|
}
|
|
if Trim(declaration[at:]) != ";" { result.error = .ForeignEnd }
|
|
return result
|
|
}
|
|
|
|
// As with other compiler rewrites, an empty output measures storage and a
|
|
// shorter one receives only its prefix. The C boundary owns termination.
|
|
ResolveForeignTarget :: (declaration: ForeignDeclaration, library: string,
|
|
output: []u8, name_limit: s64 = 128) -> ForeignTarget {
|
|
result: ForeignTarget
|
|
result.error = declaration.error
|
|
if result.error != .None || !declaration.present { return result }
|
|
go := library.count >= 3 && library[0:3] == "go:"
|
|
method: MethodSymbol
|
|
if !declaration.is_type && go {
|
|
method = ForeignMethod(declaration.symbol, name_limit, name_limit)
|
|
}
|
|
if !Source.IdentifierText(declaration.symbol, false) && !method.valid {
|
|
result.error = .ForeignSymbol
|
|
return result
|
|
}
|
|
if library == "host_api" {
|
|
if declaration.symbol != declaration.name { result.error = .ForeignHostRename }
|
|
} else if method.valid {
|
|
Put(output, *result.count, library)
|
|
Put(output, *result.count, ".(")
|
|
Put(output, *result.count, method.receiver)
|
|
Put(output, *result.count, ").")
|
|
Put(output, *result.count, method.method)
|
|
} else if go || Find(library, "/") >= 0 {
|
|
Put(output, *result.count, library)
|
|
Put(output, *result.count, ".")
|
|
Put(output, *result.count, declaration.symbol)
|
|
} else {
|
|
Put(output, *result.count, "c.")
|
|
Put(output, *result.count, declaration.symbol)
|
|
}
|
|
if result.error != .None { return result }
|
|
if declaration.go_results && !go { result.error = .ForeignGoResults }
|
|
else if declaration.go_field && !go { result.error = .ForeignGoField }
|
|
else if declaration.go_defer && !go { result.error = .ForeignGoDefer }
|
|
else if declaration.go_variadic && !go { result.error = .ForeignGoVariadic }
|
|
return result
|
|
}
|
|
|
|
ForeignVarargs :: (parameters: string) -> bool {
|
|
if Trim(parameters).count == 0 { return false }
|
|
at: s64 = 0
|
|
last := ""
|
|
while at >= 0 {
|
|
range := Text.NextSourcePart(parameters, at)
|
|
last = Trim(parameters[range.begin:range.end])
|
|
at = range.next
|
|
}
|
|
colon := Find(last, ":")
|
|
if colon >= 0 { last = Trim(last[colon + 1:]) }
|
|
return last == "..any"
|
|
}
|
|
|
|
// Types and template parameters borrow the input. Only type parameters that
|
|
// occur in the results belong to the generated record, in first-use order.
|
|
ParseResults :: (source: string, template_parameters: string) -> ResultDeclaration {
|
|
result: ResultDeclaration
|
|
list := Trim(source)
|
|
named := list.count > 1 && list[0] == #char "(" &&
|
|
Source.ClosingParenthesis(list) == list.count - 1 && Find(list, ":") >= 0
|
|
if named { list = list[1:list.count - 1] }
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
if result.count == 16 { result.error = .ResultCount; return result }
|
|
range := Text.NextSourcePart(list, at)
|
|
result.types[result.count] = Trim(list[range.begin:range.end])
|
|
result.count += 1
|
|
at = range.next
|
|
}
|
|
if result.count < 2 { result.count = 0; return result }
|
|
for index: 0..result.count - 1 {
|
|
part := result.types[index]
|
|
if named {
|
|
colon := Find(part, ":")
|
|
if colon < 0 || !Source.IdentifierText(Trim(part[0:colon]), false) {
|
|
result.error = .ResultName
|
|
return result
|
|
}
|
|
part = Trim(part[colon + 1:])
|
|
result.types[index] = part
|
|
}
|
|
if part.count == 0 || Find(part, "$") >= 0 || Find(part, "\0") >= 0 {
|
|
result.error = .ResultType
|
|
return result
|
|
}
|
|
cursor: s64 = 0
|
|
while cursor < part.count {
|
|
if !Source.IdentifierText(part[cursor:cursor + 1], false) { cursor += 1; continue }
|
|
begin := cursor
|
|
cursor += 1
|
|
while cursor < part.count && Text.IdentifierByte(part[cursor]) { cursor += 1 }
|
|
parameter := part[begin:cursor]
|
|
if !ParameterIn(template_parameters, parameter) { continue }
|
|
seen := false
|
|
for previous: 0..result.parameter_count - 1 {
|
|
if result.parameters[previous] == parameter { seen = true }
|
|
}
|
|
if seen { continue }
|
|
if result.parameter_count == 64 { result.error = .ResultParameters; return result }
|
|
result.parameters[result.parameter_count] = parameter
|
|
result.parameter_count += 1
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// Output functions measure the complete spelling even when only a prefix fits.
|
|
// The C boundary checks its storage limits before installing a results type.
|
|
ResultsRecord :: (results: ResultDeclaration, output: []u8) -> s64 {
|
|
used: s64 = 0
|
|
Put(output, *used, "Results")
|
|
for index: 0..results.count - 1 {
|
|
Put(output, *used, "__")
|
|
for byte: results.types[index] {
|
|
if Text.SpaceByte(byte) { continue }
|
|
normalized := byte
|
|
if !Text.IdentifierByte(byte) {
|
|
normalized = #char "_"
|
|
if byte == #char "*" { normalized = #char "p" }
|
|
else if byte == #char "[" { normalized = #char "a" }
|
|
}
|
|
PutByte(output, *used, normalized)
|
|
}
|
|
}
|
|
return used
|
|
}
|
|
ResultsParameters :: (results: ResultDeclaration, output: []u8) -> s64 {
|
|
used: s64 = 0
|
|
for index: 0..results.parameter_count - 1 {
|
|
if index > 0 { Put(output, *used, ",") }
|
|
Put(output, *used, results.parameters[index])
|
|
}
|
|
return used
|
|
}
|
|
ResultsBody :: (results: ResultDeclaration, output: []u8) -> s64 {
|
|
used: s64 = 0
|
|
for index: 0..results.count - 1 {
|
|
Put(output, *used, "value_")
|
|
if index >= 10 { Put(output, *used, "1") }
|
|
PutByte(output, *used, cast(u8)(#char "0" + index % 10))
|
|
Put(output, *used, ": ")
|
|
Put(output, *used, results.types[index])
|
|
Put(output, *used, "\n")
|
|
}
|
|
return used
|
|
}
|
|
|
|
RewriteResultReturn :: (source: string, record: string, results: s32, output: []u8) -> ResultReturn {
|
|
result: ResultReturn
|
|
body := Trim(source)
|
|
if !Source.StartsWord(body, "return") { return result }
|
|
value := StatementValue(body[6:])
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
range := Text.NextSourcePart(value, at)
|
|
result.values += 1
|
|
at = range.next
|
|
}
|
|
if result.values < 2 { return result }
|
|
result.present = true
|
|
if result.values != results { result.error = .ReturnCount; return result }
|
|
Put(output, *result.count, "return ")
|
|
Put(output, *result.count, record)
|
|
Put(output, *result.count, ".{")
|
|
Put(output, *result.count, value)
|
|
Put(output, *result.count, "};")
|
|
return result
|
|
}
|
|
|
|
MultipleBinding :: (source: string, maximum: s32 = 16, name_limit: s64 = 128) -> ResultBinding {
|
|
result: ResultBinding
|
|
at := Text.SkipSpace(source, 0, true)
|
|
while at < source.count {
|
|
begin := at
|
|
while at < source.count && Text.IdentifierByte(source[at]) { at += 1 }
|
|
name := source[begin:at]
|
|
if name.count >= name_limit || !Source.IdentifierText(name, false) ||
|
|
result.count == 16 || result.count >= maximum { return .{} }
|
|
result.targets[result.count] = name
|
|
result.count += 1
|
|
at = Text.SkipSpace(source, at, true)
|
|
if at >= source.count || source[at] != #char "," { break }
|
|
at = Text.SkipSpace(source, at + 1, true)
|
|
}
|
|
if result.count < 2 || at >= source.count { return .{} }
|
|
if source[at] == #char ":" && at + 1 < source.count && source[at + 1] == #char "=" {
|
|
result.inferred = true
|
|
at += 2
|
|
} else if source[at] == #char "=" && (at + 1 == source.count || source[at + 1] != #char "=") {
|
|
at += 1
|
|
} else { return .{} }
|
|
result.value = StatementValue(source[at:])
|
|
if result.value.count == 0 { return .{} }
|
|
result.present = true
|
|
return result
|
|
}
|
|
|
|
#scope_file
|
|
ParameterIn :: (source: string, parameter: string) -> bool {
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
range := Text.NextSourcePart(source, at)
|
|
if Trim(source[range.begin:range.end]) == parameter { return true }
|
|
at = range.next
|
|
}
|
|
return false
|
|
}
|
|
StatementValue :: (source: string) -> string {
|
|
value := Trim(source)
|
|
while value.count > 0 && value[value.count - 1] == #char ";" {
|
|
value = Trim(value[0:value.count - 1])
|
|
}
|
|
return value
|
|
}
|
|
PutByte :: (output: []u8, used: *s64, byte: u8) {
|
|
if <<used < output.count { output[<<used] = byte }
|
|
<<used += 1
|
|
}
|
|
|
|
// Preprocessing removes comments before the C frontend calls these rules;
|
|
// direct callers still get bounded scanning and literal/comment preservation.
|
|
AfterComment :: (source: string, at: s64) -> s64 {
|
|
if at + 1 >= source.count || source[at] != #char "/" { return at }
|
|
if source[at + 1] == #char "/" { return source.count }
|
|
if source[at + 1] != #char "*" { return at }
|
|
at += 2
|
|
depth: s32 = 1
|
|
while at < source.count && depth > 0 {
|
|
if at + 1 < source.count && source[at] == #char "/" && source[at + 1] == #char "*" {
|
|
depth += 1; at += 2
|
|
} else if at + 1 < source.count && source[at] == #char "*" && source[at + 1] == #char "/" {
|
|
depth -= 1; at += 2
|
|
} else { at += 1 }
|
|
}
|
|
return at
|
|
}
|
|
|
|
#scope_export
|
|
DefaultScopeIndependent :: (source: string, token_limit: s64 = 8192) -> bool {
|
|
previous := ""
|
|
at: s64 = 0
|
|
while at < source.count {
|
|
token := Scan.NextToken(source, at, 1, 1)
|
|
if token.kind == Scan.TokenKind.Eof { return true }
|
|
spelling := source[token.begin:token.end]
|
|
if token.kind == Scan.TokenKind.Unknown || spelling.count >= token_limit { return false }
|
|
if token.kind == Scan.TokenKind.Directive && spelling != "#char" { return false }
|
|
if token.kind == Scan.TokenKind.Ident && spelling != "true" && spelling != "false" && spelling != "null" {
|
|
next := Scan.NextToken(source, token.end, 1, 1)
|
|
if (previous != "{" && previous != ",") || source[next.begin:next.end] != "=" { return false }
|
|
}
|
|
previous = spelling
|
|
at = token.end
|
|
}
|
|
return true
|
|
}
|
|
|
|
RewriteProcedureName :: (source: string, name: string, output: []u8) -> TextRewrite {
|
|
result: TextRewrite
|
|
copied: s64 = 0
|
|
at: s64 = 0
|
|
while at < source.count {
|
|
token := Scan.NextToken(source, at, 1, 1)
|
|
if token.kind == Scan.TokenKind.Eof { break }
|
|
comment := AfterComment(source, token.begin)
|
|
if comment != token.begin { at = comment; continue }
|
|
at = token.end
|
|
if token.kind != Scan.TokenKind.Directive || source[token.begin:token.end] != "#procedure_name" { continue }
|
|
opening := Scan.NextToken(source, at, 1, 1)
|
|
closing := Scan.NextToken(source, opening.end, 1, 1)
|
|
if source[opening.begin:opening.end] != "(" || source[closing.begin:closing.end] != ")" {
|
|
result.error = .ProcedureNameArguments
|
|
return result
|
|
}
|
|
Put(output, *result.count, source[copied:token.begin])
|
|
Put(output, *result.count, "\"")
|
|
Put(output, *result.count, name)
|
|
Put(output, *result.count, "\"")
|
|
at = closing.end
|
|
copied = at
|
|
result.changed = true
|
|
}
|
|
Put(output, *result.count, source[copied:])
|
|
return result
|
|
}
|
|
|
|
RewriteLocalNames :: (source: string, names: []NameReplacement, output: []u8) -> TextRewrite {
|
|
result: TextRewrite
|
|
previous := ""
|
|
copied: s64 = 0
|
|
at: s64 = 0
|
|
while at < source.count {
|
|
token := Scan.NextToken(source, at, 1, 1)
|
|
if token.kind == Scan.TokenKind.Eof { break }
|
|
comment := AfterComment(source, token.begin)
|
|
if comment != token.begin { at = comment; continue }
|
|
spelling := source[token.begin:token.end]
|
|
label := false
|
|
if previous == "{" || previous == "," || previous == "(" {
|
|
next := Scan.NextToken(source, token.end, 1, 1)
|
|
label = source[next.begin:next.end] == "="
|
|
}
|
|
if token.kind == Scan.TokenKind.Ident && previous != "." && !label {
|
|
for < index: 0..names.count - 1 {
|
|
if names[index].source != spelling { continue }
|
|
Put(output, *result.count, source[copied:token.begin])
|
|
Put(output, *result.count, names[index].target)
|
|
copied = token.end
|
|
result.changed = true
|
|
break
|
|
}
|
|
}
|
|
previous = spelling
|
|
at = token.end
|
|
}
|
|
Put(output, *result.count, source[copied:])
|
|
return result
|
|
}
|
|
|
|
RewriteSymmetric :: (source: string, header_output: []u8, wrapper_output: []u8,
|
|
name_limit: s64 = 128) -> SymmetricRewrite {
|
|
result: SymmetricRewrite
|
|
directive: s64 = -1
|
|
end: s64 = 0
|
|
at: s64 = 0
|
|
depth: s32 = 0
|
|
while at < source.count {
|
|
token := Scan.NextToken(source, at, 1, 1)
|
|
if token.kind == Scan.TokenKind.Eof { break }
|
|
comment := AfterComment(source, token.begin)
|
|
if comment != token.begin { at = comment; continue }
|
|
spelling := source[token.begin:token.end]
|
|
if spelling == "(" || spelling == "[" || spelling == "{" { depth += 1 }
|
|
else if spelling == ")" || spelling == "]" || spelling == "}" { depth -= 1 }
|
|
if spelling == "{" && depth == 1 { break }
|
|
if depth == 0 && token.kind == Scan.TokenKind.Directive && spelling == "#symmetric" {
|
|
if directive >= 0 { result.error = .SymmetricModifier; return result }
|
|
directive = token.begin
|
|
end = token.end
|
|
}
|
|
at = token.end
|
|
}
|
|
if directive < 0 { Put(header_output, *result.header_count, source); return result }
|
|
result.present = true
|
|
Put(header_output, *result.header_count, source[0:directive])
|
|
Put(header_output, *result.header_count, source[end:])
|
|
header := Source.ProcedureHeaderParts(source)
|
|
if header.name.count < 9 || header.name[0:9] != "operator_" || header.name.count >= name_limit {
|
|
result.error = .SymmetricParameters
|
|
return result
|
|
}
|
|
first := Text.NextSourcePart(header.parameters, 0)
|
|
second := Text.NextSourcePart(header.parameters, first.next)
|
|
if first.next < 0 || second.next >= 0 { result.error = .SymmetricParameters; return result }
|
|
left := Trim(header.parameters[first.begin:first.end])
|
|
right := Trim(header.parameters[second.begin:second.end])
|
|
left_colon := Find(left, ":")
|
|
right_colon := Find(right, ":")
|
|
if left_colon < 0 || right_colon < 0 { result.error = .SymmetricParameters; return result }
|
|
left_name := Trim(left[0:left_colon])
|
|
right_name := Trim(right[0:right_colon])
|
|
if left_name.count >= name_limit || right_name.count >= name_limit ||
|
|
!Source.IdentifierText(left_name, false) || !Source.IdentifierText(right_name, false) {
|
|
result.error = .SymmetricParameters
|
|
return result
|
|
}
|
|
first_type: [128]u8
|
|
second_type: [128]u8
|
|
result_type: [128]u8
|
|
left_count := Source.NormalizeTypeSpacing(Trim(left[left_colon + 1:]), first_type[:])
|
|
right_count := Source.NormalizeTypeSpacing(Trim(right[right_colon + 1:]), second_type[:])
|
|
if left_count == 0 || right_count == 0 || left_count >= 128 || right_count >= 128 {
|
|
result.error = .SymmetricParameters
|
|
return result
|
|
}
|
|
left_type := TextView(first_type[0:left_count])
|
|
right_type := TextView(second_type[0:right_count])
|
|
if left_type == right_type { return result }
|
|
result_count := Source.NormalizeTypeSpacing(header.result, result_type[:])
|
|
if result_count >= 128 { result.error = .SymmetricParameters; return result }
|
|
return_type := TextView(result_type[0:result_count])
|
|
result.needed = true
|
|
Put(wrapper_output, *result.count, header.name)
|
|
Put(wrapper_output, *result.count, " :: (")
|
|
Put(wrapper_output, *result.count, right_name)
|
|
Put(wrapper_output, *result.count, ": ")
|
|
Put(wrapper_output, *result.count, right_type)
|
|
Put(wrapper_output, *result.count, ", ")
|
|
Put(wrapper_output, *result.count, left_name)
|
|
Put(wrapper_output, *result.count, ": ")
|
|
Put(wrapper_output, *result.count, left_type)
|
|
Put(wrapper_output, *result.count, ")")
|
|
if return_type != "void" {
|
|
Put(wrapper_output, *result.count, " -> ")
|
|
Put(wrapper_output, *result.count, return_type)
|
|
}
|
|
Put(wrapper_output, *result.count, " { return ")
|
|
Put(wrapper_output, *result.count, header.name)
|
|
Put(wrapper_output, *result.count, "(")
|
|
Put(wrapper_output, *result.count, left_name)
|
|
Put(wrapper_output, *result.count, ", ")
|
|
Put(wrapper_output, *result.count, right_name)
|
|
Put(wrapper_output, *result.count, "); }")
|
|
return result
|
|
}
|
|
|
|
// Each output slot receives its bounded statement prefix. Missing slots still
|
|
// get measured, so callers can size storage without retaining native buffers.
|
|
BuilderPrintPieces :: (source: string, output: []StatementOutput, maximum: s32 = 64) -> PrintRewrite {
|
|
result: PrintRewrite
|
|
call := Trim(source)
|
|
if !Source.StartsWord(call, "BuilderPrint") { return result }
|
|
opening := Text.SkipSpace(call, 12, true)
|
|
if opening >= call.count || call[opening] != #char "(" { return result }
|
|
closing := Source.ClosingParenthesis(call[opening:])
|
|
if closing < 0 { return result }
|
|
closing += opening
|
|
rest := Trim(call[closing + 1:])
|
|
if rest != "" && rest != ";" { return result }
|
|
inner := call[opening + 1:closing]
|
|
parts: [64]string
|
|
count: s32 = 0
|
|
at: s64 = 0
|
|
while at >= 0 {
|
|
if count == 64 { result.error = .BuilderArgumentCount; return result }
|
|
range := Text.NextSourcePart(inner, at)
|
|
parts[count] = Trim(inner[range.begin:range.end])
|
|
count += 1
|
|
at = range.next
|
|
}
|
|
format := parts[1]
|
|
if count < 2 || format.count < 2 || format[0] != #char "\"" || format[format.count - 1] != #char "\"" {
|
|
result.error = .BuilderFormat
|
|
return result
|
|
}
|
|
format = format[1:format.count - 1]
|
|
argument: s32 = 2
|
|
begin: s64 = 0
|
|
at = 0
|
|
while at < format.count {
|
|
byte := format[at]
|
|
if byte == #char "\\" && at + 1 < format.count { at += 2; continue }
|
|
if byte == #char "%" && at + 1 < format.count && format[at + 1] == #char "%" { at += 2; continue }
|
|
if byte != #char "%" { at += 1; continue }
|
|
if argument == count { result.error = .BuilderPercent; return result }
|
|
if at > begin { AddPrintPiece(*result, output, maximum, parts[0], format[begin:at], true) }
|
|
if result.error != .None { return result }
|
|
AddPrintPiece(*result, output, maximum, parts[0], parts[argument], false)
|
|
if result.error != .None { return result }
|
|
argument += 1
|
|
at += 1
|
|
begin = at
|
|
}
|
|
if argument != count { result.error = .BuilderArguments; return result }
|
|
if at > begin { AddPrintPiece(*result, output, maximum, parts[0], format[begin:at], true) }
|
|
return result
|
|
}
|
|
|
|
#scope_file
|
|
AddPrintPiece :: (result: *PrintRewrite, output: []StatementOutput, maximum: s32,
|
|
builder: string, value: string, literal: bool) {
|
|
if result.statements == 64 || result.statements >= maximum { result.error = .BuilderPieces; return }
|
|
slot: []u8
|
|
if result.statements < output.count { slot = output[result.statements].bytes }
|
|
used: s64 = 0
|
|
Put(slot, *used, "Append(")
|
|
Put(slot, *used, builder)
|
|
Put(slot, *used, ", ")
|
|
if literal {
|
|
Put(slot, *used, "\"")
|
|
at: s64 = 0
|
|
while at < value.count {
|
|
byte := value[at]
|
|
PutByte(slot, *used, byte)
|
|
at += 1
|
|
if byte == #char "\\" && at < value.count { PutByte(slot, *used, value[at]); at += 1 }
|
|
else if byte == #char "%" && at < value.count && value[at] == #char "%" { at += 1 }
|
|
}
|
|
Put(slot, *used, "\"")
|
|
} else { Put(slot, *used, value) }
|
|
Put(slot, *used, ");")
|
|
result.lengths[result.statements] = used
|
|
result.statements += 1
|
|
}
|