diff --git a/README.md b/README.md index f5dba3e37..581b65859 100644 --- a/README.md +++ b/README.md @@ -32,9 +32,9 @@ It contains the reference compiler, API, and standard library. - Easy low-level programming - High [interoperability](https://manual.jule.dev/integrated-jule/interoperability/) with C, C++, Objective-C and Objective-C++ - Disable variable shadowing by default, immutability by default, boundary checking, no uninitialized memory -- The [API](https://manual.jule.dev/api/) written in C++ and allows extend Jule thanks to interoperability +- The [API](https://manual.jule.dev/api/) written in Jule and C++ and allows extend Jule with C++ thanks to interoperability -![image](https://github.com/julelang/jule/assets/54983926/e8b28748-9212-4db8-9f7b-0b0d33dc878b) +![image](https://github.com/user-attachments/assets/0a6aee7c-6f0c-4ec1-96f8-d02b7fdc034c) > [!IMPORTANT] > Jule does not have a stable version yet and is still being developed to become more stable. diff --git a/api/runtime.hpp b/api/runtime.hpp index 61b426129..b78c6e137 100644 --- a/api/runtime.hpp +++ b/api/runtime.hpp @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -// Declarations of the exported defines of the [std::runtime] package. +// Declarations of the exported defines of the "std/runtime" package. // Implemented by compiler via generation object code for the package. #ifndef __JULE_RUNTIME_HPP diff --git a/src/julec/README.md b/src/julec/README.md index 3641bc89f..020d3e4f3 100644 --- a/src/julec/README.md +++ b/src/julec/README.md @@ -9,7 +9,7 @@ That's why paths are adjusted accordingly. # Introduction to JuleC -> Some important parts of the reference compiler are publicly available in the standard library. See [`std::jule`](https://github.com/julelang/jule/tree/master/std/jule) library. +> Some important parts of the reference compiler are publicly available in the standard library. See [`std/jule`](https://github.com/julelang/jule/tree/master/std/jule) library. JuleC @@ -40,7 +40,7 @@ This stage is the stage where the compiler generates object code. ### 1. Lexer -The package [``./lex``](https://github.com/julelang/jule/tree/master/std/jule/lex) is Lexer. \ +The package [``./token``](https://github.com/julelang/jule/tree/master/std/jule/token) is Lexer. \ Makes lexical analysis and segments Jule source code into tokens. ### 2. Parser diff --git a/src/julec/compile.jule b/src/julec/compile.jule index 6b33c04b2..373282010 100644 --- a/src/julec/compile.jule +++ b/src/julec/compile.jule @@ -2,33 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use env -use opt::{self, OptLevel, Optimizer} -use handle::{AnsiEscape, Logger, Throw} -use obj::{IR} -use cxx for obj::cxx -use std::flag::{FlagSet} -use std::fs::{FsError, OFlag, File, Directory, Status} -use path for std::fs::path -use integrated for std::jule::integrated -use std::jule::sema::{ - ImportInfo, - Package, - SemaFlag, -} -use build for std::jule::build::{ - self, - LogMsg, - Log, - PathStdlib, - EntryPoint, - InitFn, - Logf, - IsValidCppExt, -} -use types for std::jule::types -use std::process::{ProcessError, Cmd} -use strings for std::strings::{StrBuilder} +use "env" +use "handle" +use "obj" +use "obj/cxx" +use "opt" +use "std/flag" +use "std/fs" +use "std/fs/path" +use "std/jule/build" +use integ "std/jule/integrated" +use "std/jule/sema" +use "std/jule/types" +use "std/process" +use "std/strings" static mut OutDir = "dist" static mut OutName = "ir.cpp" @@ -40,24 +27,24 @@ fn init() { env::Compiler = "clang" } -fn openOutput(&path: str): &File { +fn openOutput(&path: str): &fs::File { dir := path::Dir(path) - Status.Of(dir) else { - Directory.Create(dir) else { - Throw("a problem occurs when code generation") + fs::Status.Of(dir) else { + fs::Directory.Create(dir) else { + handle::Throw("a problem occurs when code generation") } } - ret File.Create(path) else { - Throw("a problem occurs when code generation") + ret fs::File.Create(path) else { + handle::Throw("a problem occurs when code generation") use nil } } // Remove generated objects for compilation. fn clearObjects() { - File.Remove(getCompilePath()) else { + fs::File.Remove(getCompilePath()) else { outln("a problem occurs when object cleaning") ret } @@ -65,23 +52,23 @@ fn clearObjects() { // All created objects are cleaned. // So, deletes directory if empty after cleaned all objects, // if not, leaves the directory. - Directory.Remove(OutDir) else {} + fs::Directory.Remove(OutDir) else {} } // Compie generated IR. fn compileIr(compiler: str, compilerCmd: str) { - mut cmd := Cmd.New(compiler) + mut cmd := process::Cmd.New(compiler) cmd.Args = strings::Split(compilerCmd, " ", -1) cmd.Spawn() else { match error { - | ProcessError.NotExist: - AnsiEscape.Print(AnsiEscape.RedSeq, "back-end compiler could not used because of compiler path is not exist") - | ProcessError.Denied: - AnsiEscape.Print(AnsiEscape.RedSeq, "back-end compiler could not used because of permission denied") + | process::ProcessError.NotExist: + handle::AnsiEscape.Print(handle::AnsiEscape.RedSeq, "back-end compiler could not used because of compiler path is not exist") + | process::ProcessError.Denied: + handle::AnsiEscape.Print(handle::AnsiEscape.RedSeq, "back-end compiler could not used because of permission denied") |: - AnsiEscape.Print(AnsiEscape.RedSeq, "back-end compiler could not used because of unknown problem") + handle::AnsiEscape.Print(handle::AnsiEscape.RedSeq, "back-end compiler could not used because of unknown problem") } - Throw("") + handle::Throw("") } status := cmd.Wait()! if status != 0 { @@ -89,8 +76,8 @@ fn compileIr(compiler: str, compilerCmd: str) { >>> please check errors above >>> is this a compiler problem, please report us: https://github.com/julelang/jule/issues/new/choose` - AnsiEscape.Print(AnsiEscape.RedSeq, errorMessage) - Throw("") + handle::AnsiEscape.Print(handle::AnsiEscape.RedSeq, errorMessage) + handle::Throw("") } clearObjects() @@ -101,10 +88,10 @@ fn isCppSourceFile(path: str): bool { if offset == -1 { ret false } - ret IsValidCppExt(path[offset:]) + ret build::IsValidCppExt(path[offset:]) } -fn pushCompCmdClang(mut &cmd: StrBuilder) { +fn pushCompCmdClang(mut &cmd: strings::Builder) { // Disable all warnings. cmd.WriteStr("-Wno-everything ") @@ -130,7 +117,7 @@ fn pushCompCmdClang(mut &cmd: StrBuilder) { } } -fn pushCompCmdGcc(mut &cmd: StrBuilder) { +fn pushCompCmdGcc(mut &cmd: strings::Builder) { // Disable all warnings. cmd.WriteStr("-w ") @@ -156,9 +143,9 @@ fn pushCompCmdGcc(mut &cmd: StrBuilder) { } // Generate compile command for backend-compiler. -fn genCompileCmd(sourcePath: str, &ir: &IR): (str, str) { +fn genCompileCmd(sourcePath: str, &ir: &obj::IR): (str, str) { &compiler := env::CompilerPath - mut cmd := StrBuilder.New(1 << 6) + mut cmd := strings::Builder.New(1 << 6) match env::Compiler { | "gcc": @@ -202,15 +189,15 @@ fn getCompilePath(): str { ret path::Join(OutDir, OutName) } -fn applyTargetIndependentOptimizations(mut &ir: &IR) { - mut opt := Optimizer.New(ir) +fn applyTargetIndependentOptimizations(mut &ir: &obj::IR) { + mut opt := opt::Optimizer.New(ir) opt.Optimize() } fn checkCompilerFlag() { match env::Compiler { | "": - Throw("missing option value: --compiler") + handle::Throw("missing option value: --compiler") | "clang": if env::CompilerPath == "" { env::CompilerPath = "clang++" @@ -220,7 +207,7 @@ fn checkCompilerFlag() { env::CompilerPath = "g++" } |: - Throw("invalid option value for --compiler: " + env::Compiler) + handle::Throw("invalid option value for --compiler: " + env::Compiler) } } @@ -228,7 +215,7 @@ fn checkTargetArch(arch: str) { if arch != build::DistArch.Amd64 && arch != build::DistArch.Arm64 && arch != build::DistArch.I386 { - Throw("--target: unsupported/undefined architecture: " + arch) + handle::Throw("--target: unsupported/undefined architecture: " + arch) } } @@ -236,18 +223,18 @@ fn checkTargetOs(os: str) { if os != build::DistOs.Windows && os != build::DistOs.Linux && os != build::DistOs.Darwin { - Throw("--target: unsupported/undefined operating system: " + os) + handle::Throw("--target: unsupported/undefined operating system: " + os) } } fn checkTargetFlag(&target: str) { if target == "" { - Throw("missing option value: --target") + handle::Throw("missing option value: --target") } parts := strings::Split(target, "-", -1) if len(parts) != 2 { - Throw("--target: undefined platform target format: " + target) + handle::Throw("--target: undefined platform target format: " + target) } os, arch := parts[0], parts[1] @@ -265,16 +252,16 @@ fn checkTargetFlag(&target: str) { fn checkOptFlag(&opt: str) { if opt == "" { - Throw("missing option value: --opt") + handle::Throw("missing option value: --opt") } match opt { | "L0": break | "L1": - opt::PushOptLevel(OptLevel.L1) + opt::PushOptLevel(opt::OptLevel.L1) |: - Throw("--opt: invalid optimization level: " + opt) + handle::Throw("--opt: invalid optimization level: " + opt) } } @@ -285,7 +272,7 @@ fn checkCppStdFlag() { | "cpp20": break |: - Throw("--cppstd: invalid cpp standard: " + env::CppStd) + handle::Throw("--cppstd: invalid cpp standard: " + env::CppStd) } } @@ -293,7 +280,7 @@ fn checkFlags(&args: []str): []str { mut opt := "L0" mut target := "native-native" - mut fs := FlagSet.New() + mut fs := flag::FlagSet.New() fs.AddVar[str](unsafe { (&str)(&opt) }, "opt", 0, "Optimization level") fs.AddVar[str](unsafe { (&str)(&target) }, "target", 0, "Target system") @@ -322,7 +309,7 @@ fn checkFlags(&args: []str): []str { fs.AddVar[bool](unsafe { (&bool)(&opt::Dynamic) }, "opt-dynamic", 0, "Dynamic programming optimizations") mut content := fs.Parse(args) else { - Throw(str(error)) + handle::Throw(str(error)) use nil // Avoid error. } @@ -334,46 +321,46 @@ fn checkFlags(&args: []str): []str { ret content } -fn setupSemaFlags(mut &flags: SemaFlag) { +fn setupSemaFlags(mut &flags: sema::Flag) { if env::Shadowing { - flags |= SemaFlag.Shadowing + flags |= sema::Flag.Shadowing } } -fn buildIr(&args: []str): &IR { +fn buildIr(&args: []str): &obj::IR { content := checkFlags(args) - mut semaFlags := SemaFlag.Default + mut semaFlags := sema::Flag.Default setupSemaFlags(semaFlags) if len(content) == 0 { - Throw(Logf(LogMsg.MissingCompilePath)) + handle::Throw(build::Logf(build::LogMsg.MissingCompilePath)) } else if len(content) > 1 { - Throw("undefined content: " + content[1]) + handle::Throw("undefined content: " + content[1]) } mut path, ok := path::Abs(content[0]) if !ok { - Throw("compile path could not processed because of a problem") + handle::Throw("compile path could not processed because of a problem") } // Check standard library. - inf := Status.Of(PathStdlib) else { - Throw(Logf(LogMsg.StdlibNotExist)) + inf := fs::Status.Of(build::PathStdlib) else { + handle::Throw(build::Logf(build::LogMsg.StdlibNotExist)) ret nil // Avoid error. } if !inf.IsDir() { - Throw(Logf(LogMsg.StdlibNotExist)) + handle::Throw(build::Logf(build::LogMsg.StdlibNotExist)) } - mut ir, logs := IR.Build(path, semaFlags) + mut ir, logs := obj::IR.Build(path, semaFlags) if ir == nil && logs == nil { - Throw(Logf(LogMsg.NoFileInEntryPackage, path)) + handle::Throw(build::Logf(build::LogMsg.NoFileInEntryPackage, path)) } if logs != nil { - Logger.PrintLogs(logs) - Throw("") + handle::Logger.PrintLogs(logs) + handle::Throw("") } ret ir @@ -391,9 +378,9 @@ fn compileCommand(mut &args: []str) { const Binded = false if !env::Test { - mut main := ir.Main.FindFn(EntryPoint, Binded) + mut main := ir.Main.FindFn(build::EntryPoint, Binded) if main == nil { - Throw(Logf(LogMsg.NoEntryPoint)) + handle::Throw(build::Logf(build::LogMsg.NoEntryPoint)) } } @@ -418,7 +405,7 @@ fn compileCommand(mut &args: []str) { mut file := openOutput(compPath) file.Write(unsafe { oc.Buf.Buf() }) else { - Throw("object code could not write") + handle::Throw("object code could not write") } file.Close()! diff --git a/src/julec/handle/ansi.jule b/src/julec/handle/ansi.jule index d12f67686..cd16652ab 100644 --- a/src/julec/handle/ansi.jule +++ b/src/julec/handle/ansi.jule @@ -1,7 +1,7 @@ // Copyright 2024 The Jule Programming Language. // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -struct AnsiEscape {} +struct AnsiEscape{} impl AnsiEscape { const ResetSeq = "\033[0m" diff --git a/src/julec/handle/logger.jule b/src/julec/handle/logger.jule index 8adfef986..7b9ebfb5d 100644 --- a/src/julec/handle/logger.jule +++ b/src/julec/handle/logger.jule @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use conv for std::conv -use build for std::jule::build -use strings for std::strings +use "std/conv" +use "std/jule/build" +use "std/strings" // Logger for compiler logs. -struct Logger {} +struct Logger{} impl Logger { // Prints flag log. diff --git a/src/julec/handle/throw.jule b/src/julec/handle/throw.jule index 7530f2576..7e9d56290 100644 --- a/src/julec/handle/throw.jule +++ b/src/julec/handle/throw.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use process for std::process +use "std/process" const ErrorExitCode = 1 diff --git a/src/julec/main.jule b/src/julec/main.jule index 8dad0d75d..9cfdaa1a8 100644 --- a/src/julec/main.jule +++ b/src/julec/main.jule @@ -4,12 +4,12 @@ // This is the main package of JuleC. -use env -use std::fs::{File} -use jule for std::jule -use build for std::jule::build -use std::env -use strings for std::strings::{StrBuilder} +use "env" +use stdenv "std/env" +use "std/fs" +use "std/jule" +use "std/jule/build" +use "std/strings" // Compiler commands. const CmdHelp = "help" @@ -46,7 +46,7 @@ fn help(&args: []str) { } } - mut s := StrBuilder.New(1 << 5) + mut s := strings::Builder.New(1 << 5) const Space = 5 // Space of between command name and description. for i, part in HelpMap { s.WriteStr(part[0]) @@ -120,8 +120,8 @@ fn julenv(&args: []str) { ret } outln("julec version: " + jule::Version) - outln("architecture: " + std::env::Arch) - outln("operating system: " + std::env::Os) + outln("architecture: " + stdenv::Arch) + outln("operating system: " + stdenv::Os) outln("default compiler: " + env::Compiler) outln("default C++ standard: " + env::CppStd) } @@ -140,7 +140,7 @@ fn mod(&args: []str) { match args[2] { | "init": // julec mod init - File.Write(build::ModuleFile, [], 0o660) else { + fs::File.Write(build::ModuleFile, [], 0o660) else { printErrorMessage("module could not generated because of a problem") } |: @@ -186,7 +186,7 @@ Compilation: } fn main() { - mut args := std::env::Args() + mut args := stdenv::Args() // Not started with arguments. // Here is "2" but "args" always have one element for store program name. diff --git a/src/julec/obj/cxx/expr.jule b/src/julec/obj/cxx/expr.jule index 36d63063a..d3b7b17ba 100644 --- a/src/julec/obj/cxx/expr.jule +++ b/src/julec/obj/cxx/expr.jule @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use env -use opt -use conv for std::conv -use stdenv for std::env -use fmt for std::fmt -use build for std::jule::build -use constant for std::jule::constant -use lex for std::jule::lex -use sema for std::jule::sema -use types for std::jule::types -use math for std::math -use strings for std::strings -use utf8 for std::unicode::utf8 +use "env" +use "obj" +use "opt" +use "std/conv" +use stdenv "std/env" +use "std/fmt" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/sema" +use "std/jule/token" +use "std/jule/types" +use "std/math" +use "std/strings" +use "std/unicode/utf8" const collectionIdent = "__jule_collection" const collectionItIdent = "it" @@ -135,7 +135,7 @@ impl exprCoder { self.boolean(c.ReadBool()) | c.IsF64(): match { - | c.Kind == types::TypeKind.F32: + | c.Kind == types::Kind.F32: self.float32(c) |: self.float64(c) @@ -151,11 +151,11 @@ impl exprCoder { } } - fn operatorOverloadingUnary(mut &self, mut &s: &sema::StructIns, op: lex::TokenId, mut e: compExprModel) { + fn operatorOverloadingUnary(mut &self, mut &s: &sema::StructIns, op: token::Id, mut e: compExprModel) { const Unary = true mut f := obj::FindOperator(s, op, Unary) if f == nil { - panic("unary operator overloading is not exist, this is an implementation mistake") + panic("cxx: unary operator overloading is not exist, this is an implementation mistake") } identCoder.funcIns(self.oc.Buf, f) self.oc.write("(&") @@ -163,7 +163,7 @@ impl exprCoder { self.oc.write(")") } - fn divByZeroBinary(mut &self, &op: &lex::Token, mut &l: &sema::OperandExprModel, mut &r: &sema::OperandExprModel) { + fn divByZeroBinary(mut &self, &op: &token::Token, mut &l: &sema::OperandExprModel, mut &r: &sema::OperandExprModel) { const xVar = "__jule_x" const yVar = "__jule_y" self.oc.write("({ ") @@ -191,19 +191,19 @@ impl exprCoder { self.oc.write(")(") self.oc.write(xVar) match op.Id { - | lex::TokenId.Solidus - | lex::TokenId.SolidusEq: + | token::Id.Solidus + | token::Id.SolidusEq: self.oc.write(" / ") - | lex::TokenId.Percent - | lex::TokenId.PercentEq: + | token::Id.Percent + | token::Id.PercentEq: self.oc.write(" % ") } self.oc.write(yVar) self.oc.write(")); })") } - fn _unsafeBinary(mut &self, mut &buf: strings::StrBuilder, &l: str, &r: str, - mut &lk: &sema::TypeKind, mut &rk: &sema::TypeKind, op: lex::TokenId, kind: str) { + fn _unsafeBinary(mut &self, mut &buf: strings::Builder, &l: str, &r: str, + mut &lk: &sema::TypeKind, mut &rk: &sema::TypeKind, op: token::Id, kind: str) { // Operator overloading. if lk.Struct() != nil { mut s := lk.Struct() @@ -212,14 +212,14 @@ impl exprCoder { } // Special cases for comparable types. - if op == lex::TokenId.Eqs || op == lex::TokenId.NotEq { + if op == token::Id.Eqs || op == token::Id.NotEq { match { | obj::IsAny(lk): // If this binary operator comparing type. // The left operand is will be one always. if !rk.IsNil() && !obj::IsAny(rk) { buf.WriteByte('(') - if op == lex::TokenId.NotEq { + if op == token::Id.NotEq { buf.WriteByte('!') } i := self.oc.pushAnyType(rk) @@ -238,7 +238,7 @@ impl exprCoder { arr := lk.Arr() mut f := obj::RuntimeFindFn(self.oc.ir.Runtime, obj::RuntimeFunc.arrayCmp) mut ins := obj::FindFnGenericInstance(f, arr.Elem) - if op == lex::TokenId.NotEq { + if op == token::Id.NotEq { buf.WriteByte('!') } identCoder.funcIns(buf, ins) @@ -254,7 +254,7 @@ impl exprCoder { } match op { - | lex::TokenId.Plus | lex::TokenId.Minus | lex::TokenId.Star | lex::TokenId.Shl: + | token::Id.Plus | token::Id.Minus | token::Id.Star | token::Id.Shl: // guarantee unsigned integer wrap around lp := lk.Prim() if lp != nil && types::IsUnsigInt(lp.Kind) { @@ -305,7 +305,7 @@ impl exprCoder { self.oc.write(")(") self.oc.write(yVar) self.oc.write(" >= ") - self.oc.write(conv::Itoa(types::BitsizeOf(l.Kind.Prim().Kind))) + self.oc.write(conv::Itoa(types::BitSizeOf(l.Kind.Prim().Kind))) self.oc.write(" ? 0 : ") self.oc.write(xVar) self.oc.write(" << ") @@ -333,7 +333,7 @@ impl exprCoder { self.oc.write(")(") self.oc.write(yVar) self.oc.write(" >= ") - self.oc.write(conv::Itoa(types::BitsizeOf(l.Kind.Prim().Kind))) + self.oc.write(conv::Itoa(types::BitSizeOf(l.Kind.Prim().Kind))) self.oc.write(" ? 0 : ") self.oc.write(xVar) self.oc.write(" >> ") @@ -343,19 +343,19 @@ impl exprCoder { fn binary(mut &self, mut m: &sema::BinaryExprModel) { match m.Op.Id { - | lex::TokenId.Solidus | lex::TokenId.Percent: + | token::Id.Solidus | token::Id.Percent: // Do not check division safety of structures and skip if safety disabled. if env::Safety && m.Left.Kind.Struct() == nil { self.divByZeroBinary(m.Op, m.Left, m.Right) ret } - | lex::TokenId.Shl: + | token::Id.Shl: // Do not check shifting of structures. if m.Left.Kind.Struct() == nil { self.shl(m.Left, m.Right) ret } - | lex::TokenId.Shr: + | token::Id.Shr: // Do not check shifting of structures. if m.Left.Kind.Struct() == nil { self.shr(m.Left, m.Right) @@ -394,12 +394,12 @@ impl exprCoder { } match m.Op.Id { - | lex::TokenId.Caret: + | token::Id.Caret: self.oc.write("(~(") self.possibleRefExpr(m.Expr.Model) self.oc.write("))") ret - | lex::TokenId.Star: + | token::Id.Star: if env::Production || m.Expr.Kind.Sptr() == nil { break } @@ -743,7 +743,7 @@ impl exprCoder { self.possibleRefExpr((&opt::UnsafeDerefExprModel)(m).Base.Expr.Model) ret false |: - panic("implementation mistake, this panic call should be unreachable") + panic("cxx: implementation mistake, this panic call should be unreachable") } } @@ -1346,7 +1346,7 @@ impl exprCoder { match type m.Err.Model { | &sema::Var: v := (&sema::Var)(m.Err.Model) - if v.Ident == lex::TokenKind.Error { + if v.Ident == token::Kind.Error { self.oc.write("jule::VoidExceptional{.error=std::move(except.error)}") ret } @@ -1358,7 +1358,7 @@ impl exprCoder { match type m.Err.Model { | &sema::Var: v := (&sema::Var)(m.Err.Model) - if v.Ident == lex::TokenKind.Error { + if v.Ident == token::Kind.Error { self.oc.write(">{.error=except.error}") ret } @@ -1633,7 +1633,7 @@ impl exprCoder { self.possibleRefExpr(m.Base.Expr.Model) self.oc.write(".alloc)") |: - panic("implementation mistake, this panic call should be unreachable") + panic("cxx: implementation mistake, this panic call should be unreachable") } } @@ -1650,7 +1650,7 @@ impl exprCoder { } self.oc.write(">()") |: - panic("implementation mistake, this panic call should be unreachable") + panic("cxx: implementation mistake, this panic call should be unreachable") } } @@ -1952,19 +1952,19 @@ fn sbtoa(b: byte): str { ret "\\" + seq } -fn cstrBytes(mut &s: strings::StrBuilder, ctx: str) { +fn cstrBytes(mut &s: strings::Builder, ctx: str) { for _, b in ctx { s.WriteStr(sbtoa(b)) } } -fn cstrLit(mut &s: strings::StrBuilder, ctx: str) { +fn cstrLit(mut &s: strings::Builder, ctx: str) { s.WriteByte('"') cstrBytes(s, ctx) s.WriteByte('"') } -fn ftoa(mut &s: strings::StrBuilder, f: f64, bitsize: int) { +fn ftoa(mut &s: strings::Builder, f: f64, bitsize: int) { if bitsize != 32 { if f == f64(i64(f)) { itoa(s, i64(f)) @@ -1982,7 +1982,7 @@ fn ftoa(mut &s: strings::StrBuilder, f: f64, bitsize: int) { } } -fn itoa(mut &s: strings::StrBuilder, x: i64) { +fn itoa(mut &s: strings::Builder, x: i64) { match { | x == types::MaxI64: s.WriteStr("jule::MAX_I64") @@ -1999,7 +1999,7 @@ fn itoa(mut &s: strings::StrBuilder, x: i64) { s.WriteByte('L') } -fn utoa(mut &s: strings::StrBuilder, x: u64) { +fn utoa(mut &s: strings::Builder, x: u64) { match { | x == types::MaxU64: s.WriteStr("jule::MAX_U64") @@ -2013,24 +2013,24 @@ fn utoa(mut &s: strings::StrBuilder, x: u64) { s.WriteStr("LU") } -fn operatorOverloadingBinary(mut &buf: strings::StrBuilder, mut &s: &sema::StructIns, &l: str, - &r: str, op: lex::TokenId, kind: str) { +fn operatorOverloadingBinary(mut &buf: strings::Builder, mut &s: &sema::StructIns, &l: str, + &r: str, op: token::Id, kind: str) { const Unary = false mut f := (&sema::FnIns)(nil) - if op == lex::TokenId.NotEq { - f = obj::FindOperator(s, lex::TokenId.Eqs, Unary) + if op == token::Id.NotEq { + f = obj::FindOperator(s, token::Id.Eqs, Unary) buf.WriteByte('!') } else { f = obj::FindOperator(s, op, Unary) } if f == nil { - if op == lex::TokenId.Eqs || op == lex::TokenId.NotEq { + if op == token::Id.Eqs || op == token::Id.NotEq { // Equal method not exist. Compiler will create, use default method. identCoder.structureIns(buf, s) buf.WriteStr(structDefaultEqMethodSuffix) goto common } - panic("binary operator overloading is not exist, this is an implementation mistake") + panic("cxx: binary operator overloading is not exist, this is an implementation mistake") } identCoder.funcIns(buf, f) common: diff --git a/src/julec/obj/cxx/ident.jule b/src/julec/obj/cxx/ident.jule index 2cdb98cab..75c536349 100644 --- a/src/julec/obj/cxx/ident.jule +++ b/src/julec/obj/cxx/ident.jule @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use env -use obj -use std::unsafe -use conv for std::conv -use build for std::jule::build -use lex for std::jule::lex -use sema for std::jule::sema -use utf8 for std::unicode::utf8 -use strings for std::strings +use "env" +use "obj" +use "std/conv" +use "std/jule/build" +use "std/jule/sema" +use "std/jule/token" +use "std/strings" +use "std/unicode/utf8" +use "std/unsafe" // Identifier of initialize function caller function. const initCallerIdent = "__jule_call_initializers" -struct identCoder {} +struct identCoder{} impl identCoder { const Self = "_self_" @@ -23,7 +23,7 @@ impl identCoder { // Write identifiers to buf. If identifier contains unicode runes, // handle as ASCII characters. Some backend compilers are not supports // unicode identifiers and causes compile errors. - static fn writeIdentTo(mut &buf: strings::StrBuilder, &ident: str) { + static fn writeIdentTo(mut &buf: strings::Builder, &ident: str) { for _, b in ident { if b >= utf8::RuneSelf { // ident contains unicode runes. @@ -51,7 +51,7 @@ impl identCoder { // Parameters: // - ident: Identifier. // - addr: Pointer address of package file handler. - static fn toOut(mut &buf: strings::StrBuilder, ident: str, addr: uintptr) { + static fn toOut(mut &buf: strings::Builder, ident: str, addr: uintptr) { buf.WriteByte('_') if addr != 0 { buf.WriteStr(conv::FmtUint(u64(addr), 0xF)) @@ -66,7 +66,7 @@ impl identCoder { // - row: Row of definition. // - col: Column of definition. // - ident: Identifier of definition. - static fn toLocal(mut &buf: strings::StrBuilder, row: int, col: int, &ident: str) { + static fn toLocal(mut &buf: strings::Builder, row: int, col: int, &ident: str) { buf.WriteByte('_') buf.WriteStr(conv::Itoa(row)) buf.WriteStr(conv::Itoa(col)) @@ -74,7 +74,7 @@ impl identCoder { identCoder.writeIdentTo(buf, ident) } - static fn func(mut &buf: strings::StrBuilder, mut &f: &sema::Fn) { + static fn func(mut &buf: strings::Builder, mut &f: &sema::Fn) { match { | f.Binded: buf.WriteStr(f.Ident) @@ -95,7 +95,7 @@ impl identCoder { identCoder.toOut(buf, f.Ident, uintptr(f)) } - static fn funcIns(mut &buf: strings::StrBuilder, mut &f: &sema::FnIns) { + static fn funcIns(mut &buf: strings::Builder, mut &f: &sema::FnIns) { if f.IsBuiltin() { // Do not use [identCoder.writeIdentTo] for this. // Built-in functions are always ASCII. @@ -110,12 +110,12 @@ impl identCoder { identCoder.toOut(buf, f.Decl.Ident, uintptr(f)) } - static fn traitDecl(mut &buf: strings::StrBuilder, t: &sema::Trait) { + static fn traitDecl(mut &buf: strings::Builder, t: &sema::Trait) { identCoder.toOut(buf, t.Ident, uintptr(t)) } - static fn param(mut &buf: strings::StrBuilder, &p: &sema::Param) { - if lex::IsAnonIdent(p.Ident) || lex::IsIgnoreIdent(p.Ident) { + static fn param(mut &buf: strings::Builder, &p: &sema::Param) { + if token::IsAnonIdent(p.Ident) || token::IsIgnoreIdent(p.Ident) { ret } if p.IsSelf() { @@ -129,7 +129,7 @@ impl identCoder { identCoder.toLocal(buf, p.Token.Row, p.Token.Column, p.Ident) } - static fn structure(mut &buf: strings::StrBuilder, &s: &sema::Struct) { + static fn structure(mut &buf: strings::Builder, &s: &sema::Struct) { if s.Binded { if !obj::HasDirective(s.Directives, build::Directive.Typedef) { buf.WriteStr("struct ") @@ -140,7 +140,7 @@ impl identCoder { identCoder.toOut(buf, s.Ident, uintptr(s)) } - static fn structureIns(mut &buf: strings::StrBuilder, &s: &sema::StructIns) { + static fn structureIns(mut &buf: strings::Builder, &s: &sema::StructIns) { if s.Decl.Binded || len(s.Generics) == 0 { identCoder.structure(buf, s.Decl) ret @@ -148,7 +148,7 @@ impl identCoder { identCoder.toOut(buf, s.Decl.Ident, uintptr(s)) } - static fn field(mut &buf: strings::StrBuilder, &f: &sema::Field) { + static fn field(mut &buf: strings::Builder, &f: &sema::Field) { if f.Owner.Binded { buf.WriteStr(f.Ident) ret @@ -158,13 +158,13 @@ impl identCoder { } // Returns output identifier of variable. - static fn var(mut &buf: strings::StrBuilder, mut v: &sema::Var) { + static fn var(mut &buf: strings::Builder, mut v: &sema::Var) { match { | v.Binded: buf.WriteStr(v.Ident) - | v.Ident == lex::TokenKind.Error: + | v.Ident == token::Kind.Error: buf.WriteStr("except.error") - | v.Ident == lex::TokenKind.Self: + | v.Ident == token::Kind.Self: buf.WriteStr(identCoder.Self) | v.RetOrder == -1: // The single return variable is just this one. @@ -185,32 +185,32 @@ impl identCoder { } } - static fn iterBegin(mut &buf: strings::StrBuilder, it: uintptr) { + static fn iterBegin(mut &buf: strings::Builder, it: uintptr) { buf.WriteStr("_iter_begin_") buf.WriteStr(conv::FmtUint(u64(it), 0xF)) } - static fn iterEnd(mut &buf: strings::StrBuilder, it: uintptr) { + static fn iterEnd(mut &buf: strings::Builder, it: uintptr) { buf.WriteStr("_iter_end_") buf.WriteStr(conv::FmtUint(u64(it), 0xF)) } - static fn iterNext(mut &buf: strings::StrBuilder, it: uintptr) { + static fn iterNext(mut &buf: strings::Builder, it: uintptr) { buf.WriteStr("_iter_next_") buf.WriteStr(conv::FmtUint(u64(it), 0xF)) } - static fn label(mut &buf: strings::StrBuilder, u: uintptr) { + static fn label(mut &buf: strings::Builder, u: uintptr) { buf.WriteStr("_julec_label_") buf.WriteStr(conv::FmtUint(u64(u), 0xF)) } - static fn matchEnd(mut &buf: strings::StrBuilder, m: uintptr) { + static fn matchEnd(mut &buf: strings::Builder, m: uintptr) { buf.WriteStr("_match_end_") buf.WriteStr(conv::FmtUint(u64(m), 0xF)) } - static fn caseBegin(mut &buf: strings::StrBuilder, c: uintptr) { + static fn caseBegin(mut &buf: strings::Builder, c: uintptr) { buf.WriteStr("_case_begin_") buf.WriteStr(conv::FmtUint(u64(c), 0xF)) } diff --git a/src/julec/obj/cxx/object.jule b/src/julec/obj/cxx/object.jule index 179f80d09..da673fd44 100644 --- a/src/julec/obj/cxx/object.jule +++ b/src/julec/obj/cxx/object.jule @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use env -use opt -use obj -use std::unsafe -use conv for std::conv -use comptime for std::comptime -use jule for std::jule -use build for std::jule::build -use lex for std::jule::lex -use sema for std::jule::sema -use types for std::jule::types -use path for std::fs::path -use strings for std::strings -use time for std::time +use "env" +use "obj" +use "opt" +use "std/comptime" +use "std/conv" +use "std/fs/path" +use "std/jule" +use "std/jule/build" +use "std/jule/sema" +use "std/jule/token" +use "std/jule/types" +use "std/strings" +use "std/time" +use "std/unsafe" const ctxParamIdent = "__f_ctx" const anonFnCtxSuffix = "_ctx" // Anon fn identifier suffix for ctx struct identifier. @@ -46,7 +46,7 @@ static mut generalGCPtr = &sema::TypeKind{ Kind: &sema::Sptr{ Elem: &sema::TypeKind{ Kind: &sema::Prim{ - Kind: types::TypeKind.Uintptr, + Kind: types::Kind.Uintptr, }, }, }, @@ -73,13 +73,13 @@ struct metadata { struct ObjectCoder { // Internal buffer which is commonly used. - Buf: strings::StrBuilder + Buf: strings::Builder - resultDecls: strings::StrBuilder // Struct wrappers for multi-ret function types. - anyObj: strings::StrBuilder // Type handlers and others for the type. - anonObj: strings::StrBuilder // Anonymous functions. - deallocObj: strings::StrBuilder // Deallocation function for [self.deallocated] types. - coSpawnObj: strings::StrBuilder // Wrapper defines for co-spawns. + resultDecls: strings::Builder // Struct wrappers for multi-ret function types. + anyObj: strings::Builder // Type handlers and others for the type. + anonObj: strings::Builder // Anonymous functions. + deallocObj: strings::Builder // Deallocation function for [self.deallocated] types. + coSpawnObj: strings::Builder // Wrapper defines for co-spawns. ir: &obj::IR info: SerializationInfo @@ -329,7 +329,7 @@ impl ObjectCoder { self.anyTypeMap = append(self.anyTypeMap, t) si := conv::Itoa(i) if t.Sptr() != nil { - mut elemKind := strings::StrBuilder.New(40) + mut elemKind := strings::Builder.New(40) self.tc.kind(elemKind, t.Sptr().Elem) // Deallocator function. @@ -352,7 +352,7 @@ impl ObjectCoder { self.anyObj.WriteStr(si) self.anyObj.WriteStr(" && __jule_ptrEqual(any.data.alloc, other.alloc); }\n") } else { - mut kindB := strings::StrBuilder.New(40) + mut kindB := strings::Builder.New(40) self.tc.kind(kindB, t) kind := kindB.Str() @@ -374,7 +374,7 @@ impl ObjectCoder { self.anyObj.WriteStr("_eq(void *alloc, void *other) noexcept { ") if t.Comparable() { self.anyObj.WriteStr("return ") - self.ec._unsafeBinary(self.anyObj, lmodel, rmodel, t, t, lex::TokenId.Eqs, lex::TokenKind.Eqs) + self.ec._unsafeBinary(self.anyObj, lmodel, rmodel, t, t, token::Id.Eqs, token::Kind.Eqs) self.anyObj.WriteStr("; }\n") } else { self.anyObj.WriteStr(`__jule_panic((`) @@ -456,7 +456,7 @@ impl ObjectCoder { } fn pushAndWriteMaskMapper(mut &self, mut t1: &sema::Trait, mut t2: &sema::Trait) { - mut ident := strings::StrBuilder.New(1 << 5) + mut ident := strings::Builder.New(1 << 5) ident.WriteStr("__jule_trait_offset_mapper_") ident.WriteStr(conv::FmtUint(u64(uintptr(t2)), 0xF)) ident.WriteStr("_to_") @@ -478,8 +478,8 @@ impl ObjectCoder { self.anyObj.Write(unsafe { ident.Buf() }) self.anyObj.WriteStr("(const void *" + data + ") noexcept { ") - mut t1Ident := strings::StrBuilder.New(1 << 4) - mut t2Ident := strings::StrBuilder.New(1 << 4) + mut t1Ident := strings::Builder.New(1 << 4) + mut t2Ident := strings::Builder.New(1 << 4) identCoder.traitDecl(t1Ident, t1) identCoder.traitDecl(t2Ident, t2) @@ -506,7 +506,7 @@ impl ObjectCoder { } // Writes location information of token as cstr bytes. - fn locInfo(mut &self, &t: &lex::Token) { + fn locInfo(mut &self, &t: &token::Token) { &loc := t.File.Path // Normalize path if production compilation enabled. @@ -604,7 +604,7 @@ impl ObjectCoder { } for (_, mut mins) in m.Instances { mut p := mins.Params[0] - mut kind := strings::StrBuilder.New(40) + mut kind := strings::Builder.New(40) self.tc.kind(kind, p.Kind) if !p.Decl.IsRef() { kind.WriteStr("*") @@ -716,11 +716,11 @@ impl ObjectCoder { self.write("\n") self.indent() - mut fIdent := strings::StrBuilder.New(len(f.Decl.Ident)) + mut fIdent := strings::Builder.New(len(f.Decl.Ident)) identCoder.field(fIdent, f.Decl) lmodel += unsafe { unsafe::BytesStr(fIdent.Buf()) } rmodel += unsafe { unsafe::BytesStr(fIdent.Buf()) } - self.ec._unsafeBinary(self.Buf, lmodel, rmodel, f.Kind, f.Kind, lex::TokenId.Eqs, lex::TokenKind.Eqs) + self.ec._unsafeBinary(self.Buf, lmodel, rmodel, f.Kind, f.Kind, token::Id.Eqs, token::Kind.Eqs) lmodel = lmodel[:len(lmodel)-fIdent.Len()] rmodel = lmodel[:len(rmodel)-fIdent.Len()] } @@ -735,7 +735,7 @@ impl ObjectCoder { } fn structureOperators(mut &self, mut &s: &sema::StructIns, decl: bool) { - mut sb := strings::StrBuilder.New(40) + mut sb := strings::Builder.New(40) identCoder.structureIns(sb, s) ident := sb.Str() @@ -807,7 +807,7 @@ impl ObjectCoder { // The ident parameter means this function is anon, mostly. // But this parameter not only for anonymous functions. // It also useable as custom identifiers for functions. - fn funcHead(mut &self, mut &buf: strings::StrBuilder, mut &f: &sema::FnIns, ptr: bool, ident: str) { + fn funcHead(mut &self, mut &buf: strings::Builder, mut &f: &sema::FnIns, ptr: bool, ident: str) { if !ptr && opt::Inline && !f.Decl.IsEntryPoint() { buf.WriteStr("inline ") } @@ -866,7 +866,7 @@ impl ObjectCoder { obj::IterTraitMethods(t, fn(mut &m: &sema::Fn) { mut ins := m.Instances[0] for (i, mut ip) in ins.Params[1:] { - if lex::IsAnonIdent(ip.Decl.Ident) { + if token::IsAnonIdent(ip.Decl.Ident) { ip.Decl.Ident = "_" + conv::Itoa(i) } } @@ -898,13 +898,13 @@ impl ObjectCoder { }) } - fn paramIns(mut &self, mut &buf: strings::StrBuilder, mut &p: &sema::ParamIns) { + fn paramIns(mut &self, mut &buf: strings::Builder, mut &p: &sema::ParamIns) { self.tc.paramIns(buf, p) buf.WriteByte(' ') identCoder.param(buf, p.Decl) } - fn paramsIns(mut &self, mut &buf: strings::StrBuilder, mut &f: &sema::FnIns) { + fn paramsIns(mut &self, mut &buf: strings::Builder, mut &f: &sema::FnIns) { if !f.AsAnon && len(f.Params) == 0 { buf.WriteStr("(void)") ret @@ -944,7 +944,7 @@ impl ObjectCoder { } fn var(mut &self, mut v: &sema::Var) { - if lex::IsIgnoreIdent(v.Ident) { + if token::IsIgnoreIdent(v.Ident) { ret } if v.Value != nil && v.Value.Expr != nil { @@ -1009,7 +1009,7 @@ impl ObjectCoder { fn funcTrait(mut &self, &s: &sema::StructIns, mut &f: &sema::FnIns) { f.Scope = nil - mut nident := strings::StrBuilder.New(30) + mut nident := strings::Builder.New(30) nident.WriteStr("__jule_trait_method_") nident.WriteStr(conv::FmtUint(u64(uintptr(f)), 0xF)) nident.WriteStr("_") @@ -1108,7 +1108,7 @@ impl ObjectCoder { self.write("=__jule_trait_method_") mepf, exist := self.findTraitMetMap(m) if !exist { - panic("implementation mistake, [traitDataMethods] could not found MepMap record") + panic("cxx: implementation mistake, [traitDataMethods] could not found MepMap record") } self.write(conv::FmtUint(u64(uintptr(mepf)), 0xF)) self.write("_") @@ -1118,7 +1118,7 @@ impl ObjectCoder { } fn traitData(mut &self, mut &t: &sema::Trait, i: int, mut &s: &sema::StructIns) { - mut ident := strings::StrBuilder.New(len(t.Ident)) + mut ident := strings::Builder.New(len(t.Ident)) identCoder.traitDecl(ident, t) self.write("static ") self.writeBytes(unsafe { ident.Buf() }) @@ -1303,7 +1303,7 @@ impl ObjectCoder { }`) } - fn insertBuf(mut &self, mut &buf: strings::StrBuilder, pos: int) { + fn insertBuf(mut &self, mut &buf: strings::Builder, pos: int) { if buf.Len() > 0 { mut head := make([]byte, 0, self.Buf.Len()+buf.Len()) head = append(head, unsafe { self.Buf.Buf() }[:pos]...) @@ -1373,7 +1373,7 @@ impl ObjectCoder { } // Concatenate all strings into single string. -fn concatAllParts(parts: ...&lex::Token): []byte { +fn concatAllParts(parts: ...&token::Token): []byte { mut n := 0 for _, part in parts { n += len(part.Kind) @@ -1381,7 +1381,7 @@ fn concatAllParts(parts: ...&lex::Token): []byte { if n == 0 { ret nil } - mut s := strings::StrBuilder.New(n) + mut s := strings::Builder.New(n) for _, p in parts { s.WriteStr(p.Kind) } diff --git a/src/julec/obj/cxx/scope.jule b/src/julec/obj/cxx/scope.jule index a57ccc827..0eb72d3fb 100644 --- a/src/julec/obj/cxx/scope.jule +++ b/src/julec/obj/cxx/scope.jule @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use env -use opt -use conv for std::conv -use lex for std::jule::lex -use constant for std::jule::constant -use sema for std::jule::sema -use strings for std::strings +use "env" +use "obj" +use "opt" +use "std/conv" +use "std/jule/constant" +use "std/jule/sema" +use "std/jule/token" +use "std/strings" const closureCtxIdent = "__jule_closure_ctx" const matchExpr = "_match_expr" @@ -91,7 +91,7 @@ impl scopeCoder { } fn rangeIndexIter(mut &self, mut &it: &sema::RangeIter) { - mut sb := strings::StrBuilder.New(1 << 6) + mut sb := strings::Builder.New(1 << 6) identCoder.iterBegin(sb, uintptr(it)) begin := sb.Str() sb.Clear() @@ -158,7 +158,7 @@ impl scopeCoder { } fn rangeHashmapIter(mut &self, mut &it: &sema::RangeIter) { - mut sb := strings::StrBuilder.New(1 << 6) + mut sb := strings::Builder.New(1 << 6) identCoder.iterBegin(sb, uintptr(it)) begin := sb.Str() sb.Clear() @@ -241,7 +241,7 @@ impl scopeCoder { } fn strRuneIter(mut &self, mut it: &opt::StrRuneIter) { - mut sb := strings::StrBuilder.New(1 << 6) + mut sb := strings::Builder.New(1 << 6) identCoder.iterBegin(sb, uintptr(it.Base)) begin := sb.Str() sb.Clear() @@ -523,11 +523,11 @@ impl scopeCoder { } fn operatorOverloadingAssign(mut &self, mut &s: &sema::StructIns, mut &l: &sema::OperandExprModel, - mut &r: &sema::OperandExprModel, op: lex::TokenId) { + mut &r: &sema::OperandExprModel, op: token::Id) { const Unary = false mut f := obj::FindOperator(s, op, Unary) if f == nil { - panic("binary operator overloading is not exist, this is an implementation mistake") + panic("cxx: binary operator overloading is not exist, this is an implementation mistake") } identCoder.funcIns(self.oc.Buf, f) self.oc.write("(&") @@ -539,19 +539,19 @@ impl scopeCoder { fn assign(mut &self, mut a: &sema::Assign) { match a.Op.Id { - | lex::TokenId.SolidusEq | lex::TokenId.PercentEq: + | token::Id.SolidusEq | token::Id.PercentEq: // Do not check division safety of structures and skip if safety disabled. if env::Safety && a.Left.Kind.Struct() == nil { self.divByZeroAssign(a) ret } - | lex::TokenId.ShlEq: + | token::Id.ShlEq: // Do not check shifting of structures. if a.Left.Kind.Struct() == nil { self.shl(a) ret } - | lex::TokenId.ShrEq: + | token::Id.ShrEq: // Do not check shifting of structures. if a.Left.Kind.Struct() == nil { self.shr(a) @@ -559,7 +559,7 @@ impl scopeCoder { } } - if a.Op.Id != lex::TokenId.Eq && a.Left.Kind.Struct() != nil { + if a.Op.Id != token::Id.Eq && a.Left.Kind.Struct() != nil { mut s := a.Left.Kind.Struct() self.operatorOverloadingAssign(s, a.Left, a.Right, a.Op.Id) ret @@ -733,7 +733,7 @@ impl scopeCoder { | &sema::FnCallExprModel: self.multiAssignFn(a) |: - panic("this panic call should be unreachable") + panic("cxx: this panic call should be unreachable") } } @@ -910,7 +910,7 @@ impl scopeCoder { self.oc.ec.model(r.Expr) self.oc.write(");\n") |: - panic("implementation mistake, this panic call should be unreachable") + panic("cxx: implementation mistake, this panic call should be unreachable") } } diff --git a/src/julec/obj/cxx/test.jule b/src/julec/obj/cxx/test.jule index bfa89890d..5934de602 100644 --- a/src/julec/obj/cxx/test.jule +++ b/src/julec/obj/cxx/test.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use build for std::jule::build -use sema for std::jule::sema -use strings for std::strings +use "obj" +use "std/jule/build" +use "std/jule/sema" +use "std/strings" struct TestCoder { t: &sema::StructIns @@ -108,7 +108,7 @@ impl TestCoder { ret } - mut tb := strings::StrBuilder.New(40) + mut tb := strings::Builder.New(40) self.oc.tc.structureIns(tb, self.t) self.oc.tc.asSptr(self.oc.Buf, unsafe { tb.Buf() }) self.oc.write(" _t = jule::new_ptr<") diff --git a/src/julec/obj/cxx/type.jule b/src/julec/obj/cxx/type.jule index 16dbf1c07..7bc2f119b 100644 --- a/src/julec/obj/cxx/type.jule +++ b/src/julec/obj/cxx/type.jule @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use std::unsafe -use ast for std::jule::ast -use conv for std::conv -use build for std::jule::build -use sema for std::jule::sema -use types for std::jule::types -use strings for std::strings +use "obj" +use "std/conv" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/sema" +use "std/jule/types" +use "std/strings" +use "std/unsafe" const ctxParamType = typeCoder.Ptr + "<" + typeCoder.Uintptr + ">" @@ -54,8 +54,8 @@ impl typeCoder { } // Writes given identifier as Jule type identifier. - fn toType(mut self, mut &buf: strings::StrBuilder, mut id: str) { - if id != types::TypeKind.Uintptr { + fn toType(mut self, mut &buf: strings::Builder, mut id: str) { + if id != types::Kind.Uintptr { id = types::RealKindOf(id) } buf.WriteStr("jule::") @@ -68,12 +68,12 @@ impl typeCoder { } // Generates C++ code of Prim TypeKind. - fn prim(mut self, mut &buf: strings::StrBuilder, p: &sema::Prim) { + fn prim(mut self, mut &buf: strings::Builder, p: &sema::Prim) { self.toType(buf, p.Kind) } // Generates C++ code of Tupe TypeKind. - fn tuple(mut self, mut &buf: strings::StrBuilder, mut t: &sema::Tuple) { + fn tuple(mut self, mut &buf: strings::Builder, mut t: &sema::Tuple) { buf.WriteStr("std::tuple<") for (i, mut tk) in t.Types { self.kind(buf, tk) @@ -85,21 +85,21 @@ impl typeCoder { } // Generates C++ code of smart pointer type with element type. - fn asSptr(mut self, mut &buf: strings::StrBuilder, elem: []byte) { + fn asSptr(mut self, mut &buf: strings::Builder, elem: []byte) { buf.WriteStr(typeCoder.Ptr + "<") buf.Write(elem) buf.WriteByte('>') } // Generates C++ code of smart pointer TypeKind. - fn sptr(mut self, mut &buf: strings::StrBuilder, mut sptr: &sema::Sptr) { + fn sptr(mut self, mut &buf: strings::Builder, mut sptr: &sema::Sptr) { buf.WriteStr(typeCoder.Ptr + "<") self.kind(buf, sptr.Elem) buf.WriteByte('>') } // Generates C++ code of Ptr TypeKind. - fn ptr(mut self, mut &buf: strings::StrBuilder, mut p: &sema::Ptr) { + fn ptr(mut self, mut &buf: strings::Builder, mut p: &sema::Ptr) { const CppPointerMask = "*" if p.IsUnsafe() { buf.WriteStr("void" + CppPointerMask) @@ -110,28 +110,28 @@ impl typeCoder { } // Generates C++ code of Enum TypeKind. - fn enumDecl(mut self, mut &buf: strings::StrBuilder, mut e: &sema::Enum) { + fn enumDecl(mut self, mut &buf: strings::Builder, mut e: &sema::Enum) { self.kind(buf, e.Kind.Kind) } // Generates C++ code of TypeEnum TypeKind. - fn typeEnumDecl(mut self, mut &buf: strings::StrBuilder, mut e: &sema::TypeEnum) { + fn typeEnumDecl(mut self, mut &buf: strings::Builder, mut e: &sema::TypeEnum) { buf.WriteStr(typeCoder.Any) } - fn asSlice(mut self, mut &buf: strings::StrBuilder, mut elem: &sema::TypeKind) { + fn asSlice(mut self, mut &buf: strings::Builder, mut elem: &sema::TypeKind) { buf.WriteStr(typeCoder.Slice + "<") self.kind(buf, elem) buf.WriteByte('>') } // Generates C++ code of Slc TypeKind. - fn slice(mut self, mut &buf: strings::StrBuilder, mut s: &sema::Slc) { + fn slice(mut self, mut &buf: strings::Builder, mut s: &sema::Slc) { self.asSlice(buf, s.Elem) } // Generates C++ code of Map TypeKind. - fn mapType(mut self, mut &buf: strings::StrBuilder, mut m: &sema::Map) { + fn mapType(mut self, mut &buf: strings::Builder, mut m: &sema::Map) { mut s := obj::RuntimeFindStruct(self.oc.ir.Runtime, obj::RuntimeStruct._Map) mut ins := obj::FindStructGenericInstance(s, m.Key, m.Val) buf.WriteStr("jule::Ptr<") @@ -140,12 +140,12 @@ impl typeCoder { } // Generates C++ code of Struct TypeKind. - fn structure(mut self, mut &buf: strings::StrBuilder, s: &sema::Struct) { + fn structure(mut self, mut &buf: strings::Builder, s: &sema::Struct) { identCoder.structure(buf, s) } // Generates C++ code of Struct instance TypeKind. - fn structureIns(mut self, mut &buf: strings::StrBuilder, mut s: &sema::StructIns) { + fn structureIns(mut self, mut &buf: strings::Builder, mut s: &sema::StructIns) { if !s.Decl.Binded { identCoder.structureIns(buf, s) ret @@ -169,7 +169,7 @@ impl typeCoder { } // Generates C++ code of Arr TypeKind. - fn array(mut self, mut &buf: strings::StrBuilder, mut a: &sema::Arr) { + fn array(mut self, mut &buf: strings::Builder, mut a: &sema::Arr) { buf.WriteStr(typeCoder.Array + "<") self.kind(buf, a.Elem) buf.WriteByte(',') @@ -178,7 +178,7 @@ impl typeCoder { } // Generates C++ prototype code of parameter. - fn param(mut self, mut &buf: strings::StrBuilder, mut &p: &sema::Param) { + fn param(mut self, mut &buf: strings::Builder, mut &p: &sema::Param) { if p.Variadic { buf.WriteStr(typeCoder.Slice + "<") self.kind(buf, p.Kind.Kind) @@ -192,7 +192,7 @@ impl typeCoder { } // Generates C++ prototype code of parameter instance. - fn paramIns(mut self, mut &buf: strings::StrBuilder, mut &p: &sema::ParamIns) { + fn paramIns(mut self, mut &buf: strings::Builder, mut &p: &sema::ParamIns) { if p.Decl.Variadic { buf.WriteStr(typeCoder.Slice + "<") self.kind(buf, p.Kind) @@ -206,7 +206,7 @@ impl typeCoder { } // Generates C++ code of function's result type. - fn funcResult(mut self, mut &buf: strings::StrBuilder, mut &f: &sema::Fn) { + fn funcResult(mut self, mut &buf: strings::Builder, mut &f: &sema::Fn) { if f.IsVoid() { if f.Exceptional { buf.WriteStr("jule::VoidExceptional") @@ -224,7 +224,7 @@ impl typeCoder { } // Generates C++ code of function instance's result type. - fn funcInsResult(mut self, mut &s: strings::StrBuilder, mut &f: &sema::FnIns) { + fn funcInsResult(mut self, mut &s: strings::Builder, mut &f: &sema::FnIns) { if f.Decl.IsVoid() { if f.Decl.Exceptional { s.WriteStr("jule::VoidExceptional") @@ -242,7 +242,7 @@ impl typeCoder { self.rc.codeMut1(s, f.Result) } - fn anonFunc(mut self, mut &buf: strings::StrBuilder, mut f: &sema::FnIns) { + fn anonFunc(mut self, mut &buf: strings::Builder, mut f: &sema::FnIns) { if f.Result != nil && f.Result.Tup() != nil { self.oc.pushResultIns(f) } @@ -263,14 +263,14 @@ impl typeCoder { } // Generates C++ code of Fn TypeKind. - fn func(mut self, mut &buf: strings::StrBuilder, mut f: &sema::FnIns) { + fn func(mut self, mut &buf: strings::Builder, mut f: &sema::FnIns) { buf.WriteStr(typeCoder.Fn + "<") self.anonFunc(buf, f) buf.WriteByte('>') } // Generates C++ code of TypeKind. - fn kind(mut self, mut &buf: strings::StrBuilder, mut k: &sema::TypeKind) { + fn kind(mut self, mut &buf: strings::Builder, mut k: &sema::TypeKind) { match { | k.Struct() != nil: self.structureIns(buf, k.Struct()) @@ -342,34 +342,34 @@ impl resultCoder { ret &resultCoder{tc: tc} } - fn ptr(mut self, mut &s: strings::StrBuilder, mut p: &sema::Ptr) { + fn ptr(mut self, mut &s: strings::Builder, mut p: &sema::Ptr) { s.WriteStr(resultCoder.Ptr) self.codeMut(s, p.Elem) } - fn sptr(mut self, mut &s: strings::StrBuilder, mut p: &sema::Sptr) { + fn sptr(mut self, mut &s: strings::Builder, mut p: &sema::Sptr) { s.WriteStr(resultCoder.Sptr) self.codeMut(s, p.Elem) } - fn mapType(mut self, mut &s: strings::StrBuilder, mut p: &sema::Map) { + fn mapType(mut self, mut &s: strings::Builder, mut p: &sema::Map) { s.WriteStr(resultCoder.Map) self.codeMut(s, p.Key) self.codeMut(s, p.Val) } - fn slice(mut self, mut &s: strings::StrBuilder, mut slc: &sema::Slc) { + fn slice(mut self, mut &s: strings::Builder, mut slc: &sema::Slc) { s.WriteStr(resultCoder.Slice) self.codeMut(s, slc.Elem) } - fn arr(mut self, mut &s: strings::StrBuilder, mut arr: &sema::Arr) { + fn arr(mut self, mut &s: strings::Builder, mut arr: &sema::Arr) { s.WriteStr(resultCoder.Array) s.WriteStr(conv::FmtInt(i64(arr.N), 16)) self.codeMut(s, arr.Elem) } - fn func(mut self, mut &s: strings::StrBuilder, mut f: &sema::FnIns) { + fn func(mut self, mut &s: strings::Builder, mut f: &sema::FnIns) { s.WriteStr(resultCoder.Fn) for (_, mut p) in f.Params { if p.Decl.Reference { @@ -382,14 +382,14 @@ impl resultCoder { } } - fn tup(mut self, mut &s: strings::StrBuilder, mut tup: &sema::Tuple) { + fn tup(mut self, mut &s: strings::Builder, mut tup: &sema::Tuple) { for (_, mut t) in tup.Types { s.WriteStr("__jule_tuple_") self.codeMut(s, t) } } - fn codeMut(mut self, mut &s: strings::StrBuilder, mut &t: &sema::TypeKind) { + fn codeMut(mut self, mut &s: strings::Builder, mut &t: &sema::TypeKind) { if t.Binded() { s.WriteStr(resultCoder.BindPrefix) s.WriteStr(t.BindIdent) @@ -425,11 +425,11 @@ impl resultCoder { | &sema::Tuple: self.tup(s, (&sema::Tuple)(t.Kind)) |: - panic("this panic call should be unreachable") + panic("cxx: this panic call should be unreachable") } } - fn codeMut1(mut self, mut &s: strings::StrBuilder, mut &t: &sema::TypeKind) { + fn codeMut1(mut self, mut &s: strings::Builder, mut &t: &sema::TypeKind) { mut tup := t.Tup() if tup != nil { self.tup(s, tup) @@ -439,7 +439,7 @@ impl resultCoder { } fn code(mut self, mut &t: &sema::TypeKind): []byte { - mut s := strings::StrBuilder.New(20) + mut s := strings::Builder.New(20) self.codeMut(s, t) ret unsafe { s.Buf() } } diff --git a/src/julec/obj/determine.jule b/src/julec/obj/determine.jule index efb47d1b6..6e66e3d92 100644 --- a/src/julec/obj/determine.jule +++ b/src/julec/obj/determine.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use comptime for std::comptime -use path for std::fs::path -use build for std::jule::build -use sema for std::jule::sema -use strings for std::strings +use "std/comptime" +use "std/fs/path" +use "std/jule/build" +use "std/jule/sema" +use "std/strings" // Reports whether exceptional scope s forwards exceptional. fn IsForwarded(&s: &sema::Scope): bool { @@ -88,5 +88,5 @@ fn IsStdPackage(f: str, p: str): bool { // Reports whether imp is implicitly imported. // See developer reference (9). fn IsImplicitImport(imp: &sema::ImportInfo): bool { - ret imp.Token == nil + ret imp.Decl.Token == nil } \ No newline at end of file diff --git a/src/julec/obj/expr_inspector.jule b/src/julec/obj/expr_inspector.jule index 2eddb82f9..f284bb0b9 100644 --- a/src/julec/obj/expr_inspector.jule +++ b/src/julec/obj/expr_inspector.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sema for std::jule::sema +use "std/jule/sema" // Expression model inspector. struct ExprInspector { diff --git a/src/julec/obj/ir.jule b/src/julec/obj/ir.jule index 788dacb06..e50217c0d 100644 --- a/src/julec/obj/ir.jule +++ b/src/julec/obj/ir.jule @@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use env -use ast for std::jule::ast -use build for std::jule::build -use importer for std::jule::importer -use sema for std::jule::sema +use "env" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/importer" +use "std/jule/sema" +use "std/jule/token" // Intermediate representation of code for compiler. struct IR { @@ -14,7 +15,7 @@ struct IR { Root: str Passes: []str Main: &sema::Package - Runtime: &sema::ImportInfo // std::runtime + Runtime: &sema::ImportInfo // "std/runtime" Used: []&sema::ImportInfo Ordered: OrderedDefines } @@ -26,8 +27,8 @@ impl IR { // - Returns (nil, nil) logs if path has not any Jule file. // - Returns (nil, logs) if exist any log. // - Returns IR and nil logs if everything is fine. - static fn Build(path: str, flags: sema::SemaFlag): (&IR, []build::Log) { - mut importer := importer::JuleImporter.New(buildCompileInfo()) + static fn Build(path: str, flags: sema::Flag): (&IR, []build::Log) { + mut importer := importer::Importer.New(buildCompileInfo()) const UpdateMod = true // Use root module for project if exist. mut files, mut logs := importer.ImportPackage(path, UpdateMod) if len(logs) > 0 { @@ -39,7 +40,7 @@ impl IR { ret nil, nil } - // Push std::runtime package to first file. + // Push runtime package to first file. // Each Jule program should import this standard package. mut firstFile := files[0] pushRuntimeToAST(firstFile) @@ -57,7 +58,7 @@ impl IR { ir.Passes = getAllUniquePasses(ir.Main, ir.Used) // Set up special packages. - ir.Runtime = pkg.Files[0].Imports[0] // std::runtime + ir.Runtime = pkg.Files[0].Imports[0] // runtime package ret ir, nil } @@ -174,16 +175,13 @@ fn buildCompileInfo(): importer::CompileInfo { ret info } -// See [std::jule] developer reference (9). +// See "std/jule" developer reference (9). fn pushRuntimeToAST(mut &f: &ast::AST) { mut decl := &ast::UseDecl{ Token: nil, // Nil token is a flag for implicit declaration. - LinkPath: "std::runtime", - Alias: "", - Full: false, - Selected: nil, + Path: &token::Token{Id: token::Id.Lit, Kind: `"std/runtime"`}, + Alias: nil, Binded: false, - Std: true, } f.UseDecls = append(f.UseDecls, decl) if len(f.UseDecls) > 1 { diff --git a/src/julec/obj/lookup.jule b/src/julec/obj/lookup.jule index 24eeaa0bf..8bc327617 100644 --- a/src/julec/obj/lookup.jule +++ b/src/julec/obj/lookup.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use comptime for std::comptime -use ast for std::jule::ast -use lex for std::jule::lex -use sema for std::jule::sema +use "std/comptime" +use "std/jule/ast" +use "std/jule/sema" +use "std/jule/token" // Returns directive if exist. fn FindDirective(mut &directives: []&ast::Directive, tag: str): &ast::Directive { @@ -75,66 +75,66 @@ fn FindTraitTypeOffset(t: &sema::Trait, mut k: &sema::TypeKind): int { } // Returns overloaded operator method by operator id. -fn FindOperator(mut &s: &sema::StructIns, op: lex::TokenId, unary: bool): &sema::FnIns { +fn FindOperator(mut &s: &sema::StructIns, op: token::Id, unary: bool): &sema::FnIns { match op { - | lex::TokenId.Eqs: + | token::Id.Eqs: ret s.Operators.Eq - | lex::TokenId.Gt: + | token::Id.Gt: ret s.Operators.Gt - | lex::TokenId.GtEq: + | token::Id.GtEq: ret s.Operators.GtEq - | lex::TokenId.Lt: + | token::Id.Lt: ret s.Operators.Lt - | lex::TokenId.LtEq: + | token::Id.LtEq: ret s.Operators.LtEq - | lex::TokenId.Shl: + | token::Id.Shl: ret s.Operators.Shl - | lex::TokenId.Shr: + | token::Id.Shr: ret s.Operators.Shr - | lex::TokenId.Plus: + | token::Id.Plus: if unary { ret s.Operators.Pos } ret s.Operators.Add - | lex::TokenId.Minus: + | token::Id.Minus: if unary { ret s.Operators.Neg } ret s.Operators.Sub - | lex::TokenId.Solidus: + | token::Id.Solidus: ret s.Operators.Div - | lex::TokenId.Star: + | token::Id.Star: ret s.Operators.Mul - | lex::TokenId.Percent: + | token::Id.Percent: ret s.Operators.Mod - | lex::TokenId.Amper: + | token::Id.Amper: ret s.Operators.BitAnd - | lex::TokenId.Vline: + | token::Id.Vline: ret s.Operators.BitOr - | lex::TokenId.Caret: + | token::Id.Caret: if unary { ret s.Operators.BitNot } ret s.Operators.BitXor - | lex::TokenId.PlusEq: + | token::Id.PlusEq: ret s.Operators.AddAssign - | lex::TokenId.MinusEq: + | token::Id.MinusEq: ret s.Operators.SubAssign - | lex::TokenId.SolidusEq: + | token::Id.SolidusEq: ret s.Operators.DivAssign - | lex::TokenId.StarEq: + | token::Id.StarEq: ret s.Operators.MulAssign - | lex::TokenId.PercentEq: + | token::Id.PercentEq: ret s.Operators.ModAssign - | lex::TokenId.ShlEq: + | token::Id.ShlEq: ret s.Operators.ShlAssign - | lex::TokenId.ShrEq: + | token::Id.ShrEq: ret s.Operators.ShrAssign - | lex::TokenId.VlineEq: + | token::Id.VlineEq: ret s.Operators.BitOrAssign - | lex::TokenId.AmperEq: + | token::Id.AmperEq: ret s.Operators.BitAndAssign - | lex::TokenId.CaretEq: + | token::Id.CaretEq: ret s.Operators.BitXorAssign |: ret nil @@ -154,7 +154,7 @@ lookup: } ret ins } - panic("generic instance lookup failed, this is an implementation mistake") + panic("obj: generic instance lookup failed, this is an implementation mistake") } // Returns struct instance by generics. @@ -170,5 +170,5 @@ lookup: } ret ins } - panic("generic instance lookup failed, this is an implementation mistake") + panic("obj: generic instance lookup failed, this is an implementation mistake") } \ No newline at end of file diff --git a/src/julec/obj/order.jule b/src/julec/obj/order.jule index fd6e6a99b..72f909a69 100644 --- a/src/julec/obj/order.jule +++ b/src/julec/obj/order.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sema for std::jule::sema +use "std/jule/sema" // Collection for ordered defines. struct OrderedDefines { diff --git a/src/julec/obj/runtime.jule b/src/julec/obj/runtime.jule index b99ed0bd2..1739935c8 100644 --- a/src/julec/obj/runtime.jule +++ b/src/julec/obj/runtime.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sema for std::jule::sema +use "std/jule/sema" enum RuntimeFunc: str { arrayCmp: "arrayCmp", @@ -20,7 +20,7 @@ fn RuntimeFindFn(mut &runtime: &sema::ImportInfo, ident: RuntimeFunc): &sema::Fn mut f := runtime.FindFn(ident, Binded) if f == nil { outln(ident) - panic("runtime function is not exist, this is an implementation mistake, this panic call should be unreachable") + panic("obj: runtime function is not exist, this is an implementation mistake, this panic call should be unreachable") } ret f } @@ -34,7 +34,7 @@ fn RuntimeFindStruct(mut &runtime: &sema::ImportInfo, ident: RuntimeStruct): &se const Binded = false mut f := runtime.FindStruct(ident, Binded) if f == nil { - panic("runtime struct is not exist, this is an implementation mistake, this panic call should be unreachable") + panic("obj: runtime struct is not exist, this is an implementation mistake, this panic call should be unreachable") } ret f } \ No newline at end of file diff --git a/src/julec/obj/walk.jule b/src/julec/obj/walk.jule index bba5034f0..f25c9a8fd 100644 --- a/src/julec/obj/walk.jule +++ b/src/julec/obj/walk.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sema for std::jule::sema +use "std/jule/sema" fn IterPackages(mut &ir: &IR, f: fn(mut &pkg: &sema::Package)) { for (_, mut used) in ir.Used { diff --git a/src/julec/opt/boundary.jule b/src/julec/opt/boundary.jule index 3d245f7c9..3da1ae5e3 100644 --- a/src/julec/opt/boundary.jule +++ b/src/julec/opt/boundary.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use constant for std::jule::constant -use lex for std::jule::lex -use sema for std::jule::sema +use "std/jule/constant" +use "std/jule/sema" +use "std/jule/token" const invalidBoundary = uintptr(0x0) @@ -112,7 +112,7 @@ fn fitsSize(e1: sema::ExprModel, e2: sema::ExprModel): bool { | &sema::UnaryExprModel: uem1 := (&sema::UnaryExprModel)(e1) uem2 := (&sema::UnaryExprModel)(e2) - if uem1.Op.Id != lex::TokenId.Star || uem1.Op.Id != uem2.Op.Id { + if uem1.Op.Id != token::Id.Star || uem1.Op.Id != uem2.Op.Id { ret false } ret fitsSize(uem1.Expr.Model, uem2.Expr.Model) @@ -158,7 +158,7 @@ fn getBoundaryVar(m: sema::ExprModel): uintptr { ret uintptr((&sema::StructSubIdentExprModel)(m).Field) | &sema::UnaryExprModel: uem := (&sema::UnaryExprModel)(m) - if uem.Op.Id == lex::TokenId.Star { // Dereferencing. + if uem.Op.Id == token::Id.Star { // Dereferencing. ret getBoundaryVar(uem.Expr.Model) } } diff --git a/src/julec/opt/data.jule b/src/julec/opt/data.jule index 4322f4088..73fbb19d2 100644 --- a/src/julec/opt/data.jule +++ b/src/julec/opt/data.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sema for std::jule::sema +use "std/jule/sema" static mut emptyData = new(data) diff --git a/src/julec/opt/deadcode/define.jule b/src/julec/opt/deadcode/define.jule index a81fd9643..fdecf8566 100644 --- a/src/julec/opt/deadcode/define.jule +++ b/src/julec/opt/deadcode/define.jule @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use env -use obj -use comptime for std::comptime -use build for std::jule::build -use ast for std::jule::ast -use sema for std::jule::sema +use "env" +use "obj" +use "std/comptime" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/sema" struct specialCaseDefines { runtime_Map: &sema::Struct diff --git a/src/julec/opt/deadcode/expr.jule b/src/julec/opt/deadcode/expr.jule index 880b7fd5e..0b6e78069 100644 --- a/src/julec/opt/deadcode/expr.jule +++ b/src/julec/opt/deadcode/expr.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use sema for std::jule::sema +use "obj" +use "std/jule/sema" // Dead code eliminate optimizer for expressions. struct exprDeadCode { diff --git a/src/julec/opt/deadcode/scope.jule b/src/julec/opt/deadcode/scope.jule index 80a7f135b..e856600a1 100644 --- a/src/julec/opt/deadcode/scope.jule +++ b/src/julec/opt/deadcode/scope.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use sema for std::jule::sema +use "obj" +use "std/jule/sema" // Dead code eliminate optimizer for scopes. struct scopeDeadCode { diff --git a/src/julec/opt/dynamic.jule b/src/julec/opt/dynamic.jule index b18708e62..1b4d83295 100644 --- a/src/julec/opt/dynamic.jule +++ b/src/julec/opt/dynamic.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use lex for std::jule::lex -use sema for std::jule::sema +use "obj" +use "std/jule/sema" +use "std/jule/token" const invalidDynamic = uintptr(0x0) @@ -121,7 +121,7 @@ fn getDynamicVar(m: sema::ExprModel): uintptr { ret uintptr((&sema::StructSubIdentExprModel)(m).Field) | &sema::UnaryExprModel: uem := (&sema::UnaryExprModel)(m) - if uem.Op.Id == lex::TokenId.Star { // Dereferencing. + if uem.Op.Id == token::Id.Star { // Dereferencing. ret getDynamicVar(uem.Expr.Model) } } diff --git a/src/julec/opt/equal.jule b/src/julec/opt/equal.jule index 806803604..5d1786e17 100644 --- a/src/julec/opt/equal.jule +++ b/src/julec/opt/equal.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use constant for std::jule::constant -use sema for std::jule::sema +use "std/jule/constant" +use integ "std/jule/integrated" +use "std/jule/sema" fn typeData(&m: sema::ExprModel): uintptr { ret unsafe { uintptr(integ::Emit[*unsafe]("({}).type", m)) } diff --git a/src/julec/opt/expr.jule b/src/julec/opt/expr.jule index 32fe759ac..981648a95 100644 --- a/src/julec/opt/expr.jule +++ b/src/julec/opt/expr.jule @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use env -use math for std::math -use constant for std::jule::constant -use lex for std::jule::lex -use sema for std::jule::sema -use types for std::jule::types +use "env" +use "obj" +use "std/jule/constant" +use "std/jule/sema" +use "std/jule/token" +use "std/jule/types" +use "std/math" // Expression optimizer that applies target-independent optimizations. struct exprOptimizer { @@ -39,16 +39,16 @@ impl exprOptimizer { ret false } match m.Op.Id { - | lex::TokenId.Eqs - | lex::TokenId.LtEq - | lex::TokenId.GtEq: + | token::Id.Eqs + | token::Id.LtEq + | token::Id.GtEq: // Operators used with itself: ==, <=, >=. // Evaluation will be always true. *self.model = constant::Const.NewBool(true) ret true - | lex::TokenId.NotEq - | lex::TokenId.Lt - | lex::TokenId.Gt: + | token::Id.NotEq + | token::Id.Lt + | token::Id.Gt: // Operators used with itself: !=, <, >. // Evaluation will be always false. *self.model = constant::Const.NewBool(false) @@ -78,7 +78,7 @@ impl exprOptimizer { } mut c := (&constant::Const)(m.Right.Model) match m.Op.Id { - | lex::TokenId.DblAmper: + | token::Id.DblAmper: if c.ReadBool() { // Use left operand as model directly. // Logical and with constant true exprssion is always will be true. @@ -92,7 +92,7 @@ impl exprOptimizer { *self.model = c } ret true - | lex::TokenId.DblVline: + | token::Id.DblVline: if c.ReadBool() { // Logical or with constant true expression. // Binary expression is always will be true. @@ -116,7 +116,7 @@ impl exprOptimizer { if lp == nil || !lp.IsStr() { ret false } - if m.Op.Id != lex::TokenId.Eqs && m.Op.Id != lex::TokenId.NotEq { + if m.Op.Id != token::Id.Eqs && m.Op.Id != token::Id.NotEq { ret false } match type m.Left.Model { @@ -134,7 +134,7 @@ impl exprOptimizer { } mut c := (&constant::Const)(m.Right.Model) match m.Op.Id { - | lex::TokenId.Eqs: + | token::Id.Eqs: if c.ReadStr() == "" { mut model := any(&EmptyCompareExprModel{ Expr: m.Left.Model, @@ -149,7 +149,7 @@ impl exprOptimizer { NotEq: false, }) *self.model = unsafe { *(*sema::ExprModel)(&model) } - | lex::TokenId.NotEq: + | token::Id.NotEq: if c.ReadStr() == "" { mut model := any(&EmptyCompareExprModel{ Expr: m.Left.Model, @@ -173,7 +173,7 @@ impl exprOptimizer { if !Str { ret false } - if c.ReadStr() == "" && m.Op.Id == lex::TokenId.Plus { + if c.ReadStr() == "" && m.Op.Id == token::Id.Plus { // Concatenation with empty string, use the non-constnat operand's model. *self.model = nc.Model ret true @@ -187,8 +187,8 @@ impl exprOptimizer { ret false } match m.Op.Id { - | lex::TokenId.Shl - | lex::TokenId.Shr: + | token::Id.Shl + | token::Id.Shr: // If the constant expression is shifter, use the right operand's model. if nc == m.Left { *self.model = nc.Model @@ -198,12 +198,12 @@ impl exprOptimizer { // Use zero-constant directly. *self.model = c ret true - | lex::TokenId.Star: + | token::Id.Star: c.SetI64(0) *self.model = c ret true - | lex::TokenId.Plus - | lex::TokenId.Minus: + | token::Id.Plus + | token::Id.Minus: *self.model = nc.Model ret true } @@ -237,12 +237,12 @@ impl exprOptimizer { if !isBoundaryValidType(blc.Expr.Kind) { ret } - if m.Op.Id != lex::TokenId.Gt && m.Op.Id != lex::TokenId.Eqs { + if m.Op.Id != token::Id.Gt && m.Op.Id != token::Id.Eqs { ret } // len(x) > y, len(x) == y (constant) // Max guaranteed size of x is y. - if m.Op.Id == lex::TokenId.Eqs { + if m.Op.Id == token::Id.Eqs { match type m.Right.Model { | &constant::Const: mut c := new(constant::Const, *(&constant::Const)(m.Right.Model)) // Do not mutate binary operand. @@ -260,12 +260,12 @@ impl exprOptimizer { if !isBoundaryValidType(blc.Expr.Kind) { ret } - if m.Op.Id != lex::TokenId.Lt && m.Op.Id != lex::TokenId.Eqs { + if m.Op.Id != token::Id.Lt && m.Op.Id != token::Id.Eqs { ret } // y < len(x), y (constant) == len(x) // Max guaranteed size of x is y. - if m.Op.Id == lex::TokenId.Eqs { + if m.Op.Id == token::Id.Eqs { match type m.Left.Model { | &constant::Const: mut c := new(constant::Const, *(&constant::Const)(m.Left.Model)) // Do not mutate binary operand. @@ -292,7 +292,7 @@ impl exprOptimizer { | &constant::Const: // No need to check whether constant variable is nil. // It only can be nil. - self.data.nils.pushVar(var, m.Op.Id == lex::TokenId.NotEq) + self.data.nils.pushVar(var, m.Op.Id == token::Id.NotEq) } ret } @@ -305,7 +305,7 @@ impl exprOptimizer { | &constant::Const: // No need to check whether constant variable is nil. // It only can be nil. - self.data.nils.pushVar(var, m.Op.Id == lex::TokenId.NotEq) + self.data.nils.pushVar(var, m.Op.Id == token::Id.NotEq) } ret } @@ -354,44 +354,44 @@ impl exprOptimizer { } match m.Op.Id { - | lex::TokenId.Star: + | token::Id.Star: ok, x := checkForBitShiftOpt(m.Left, m.Right) if ok { - m.Op = new(lex::Token, *m.Op) - m.Op.Id = lex::TokenId.Shl - m.Op.Kind = lex::TokenKind.Shl + m.Op = new(token::Token, *m.Op) + m.Op.Id = token::Id.Shl + m.Op.Kind = token::Kind.Shl mut c := (&constant::Const)(m.Right.Model) c.SetU64(x) // No need to set model as UnsafeBinaryExprModel, // shl is not checked at runtime, so it is optimize enough. ret } - | lex::TokenId.Solidus: + | token::Id.Solidus: ok, x := checkForBitShiftOpt(m.Left, m.Right) if ok { - m.Op = new(lex::Token, *m.Op) - m.Op.Id = lex::TokenId.Shr - m.Op.Kind = lex::TokenKind.Shr + m.Op = new(token::Token, *m.Op) + m.Op.Id = token::Id.Shr + m.Op.Kind = token::Kind.Shr mut c := (&constant::Const)(m.Right.Model) c.SetU64(x) // No need to set model as UnsafeBinaryExprModel, // shr is not checked at runtime, so it is optimize enough. ret } - | lex::TokenId.Percent: + | token::Id.Percent: mut c := (&constant::Const)(m.Right.Model) if c.AsF64() == 0b10 { - m.Op = new(lex::Token, *m.Op) - m.Op.Id = lex::TokenId.Amper - m.Op.Kind = lex::TokenKind.Amper + m.Op = new(token::Token, *m.Op) + m.Op.Id = token::Id.Amper + m.Op.Kind = token::Kind.Amper c.SetI64(1) // No need to set model as UnsafeBinaryExprModel, // bitwise and is not checked at runtime, so it is optimize enough. ret } - | lex::TokenId.Shl | lex::TokenId.Shr: + | token::Id.Shl | token::Id.Shr: // semantic anlayzer guarantees right operator is unsigned if constant - z := types::BitsizeOf(lp.Kind) + z := types::BitSizeOf(lp.Kind) s := (&constant::Const)(m.Right.Model).AsU64() if s >= u64(z) { // shifting greater than bitsize of the left operand @@ -414,11 +414,11 @@ impl exprOptimizer { ret } match m.Op.Id { - | lex::TokenId.Star: + | token::Id.Star: match type m.Expr.Model { | &sema::UnaryExprModel: mut um := (&sema::UnaryExprModel)(m.Expr.Model) - if um.Op.Id == lex::TokenId.Amper { + if um.Op.Id == token::Id.Amper { // Remove pointer overhead. // Expression is: *(&x) // Simplify to: x @@ -440,7 +440,7 @@ impl exprOptimizer { // Now this varible is safe until it mutated. self.data.nils.pushVar(var, true) } - | lex::TokenId.Amper: + | token::Id.Amper: match type m.Expr.Model { | &sema::Var: mut v := (&sema::Var)(m.Expr.Model) diff --git a/src/julec/opt/model.jule b/src/julec/opt/model.jule index ae88fe5e8..9e232816e 100644 --- a/src/julec/opt/model.jule +++ b/src/julec/opt/model.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex -use constant for std::jule::constant -use sema for std::jule::sema +use "std/jule/constant" +use "std/jule/sema" +use "std/jule/token" struct ExceptionalForwardingExprModel { Expr: &sema::FnCallExprModel @@ -31,7 +31,7 @@ struct StrCompExprModel { } struct MutSlicingExprModel { - Token: &lex::Token + Token: &token::Token Expr: sema::ExprModel Left: sema::ExprModel Right: sema::ExprModel diff --git a/src/julec/opt/nil.jule b/src/julec/opt/nil.jule index 369d020e5..19bab14af 100644 --- a/src/julec/opt/nil.jule +++ b/src/julec/opt/nil.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex -use sema for std::jule::sema +use "std/jule/sema" +use "std/jule/token" const invalidNil = uintptr(0x0) diff --git a/src/julec/opt/optimizer.jule b/src/julec/opt/optimizer.jule index 96a16bfc4..483f26ec1 100644 --- a/src/julec/opt/optimizer.jule +++ b/src/julec/opt/optimizer.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use env -use obj -use deadcode for opt::deadcode -use sema for std::jule::sema +use "env" +use "obj" +use "opt/deadcode" +use "std/jule/sema" static mut exprEnabled = false static mut scopeEnabled = false diff --git a/src/julec/opt/scope.jule b/src/julec/opt/scope.jule index 8fcc99b6b..9fcd95537 100644 --- a/src/julec/opt/scope.jule +++ b/src/julec/opt/scope.jule @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use obj -use env -use path for std::fs::path -use build for std::jule::build -use constant for std::jule::constant -use lex for std::jule::lex -use sema for std::jule::sema -use strings for std::strings +use "env" +use "obj" +use "std/fs/path" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/sema" +use "std/jule/token" +use "std/strings" // Scope optimizer that applies target-independent optimizations. struct scopeOptimizer { @@ -345,7 +345,7 @@ impl scopeOptimizer { } fn substr(mut &self, mut a: &sema::Assign): bool { - if a.Op.Id != lex::TokenId.Eq { + if a.Op.Id != token::Id.Eq { ret false } match type a.Right.Model { @@ -391,7 +391,7 @@ impl scopeOptimizer { } fn optimizeAssign(mut &self, mut assign: &sema::Assign) { - if assign.Op.Id == lex::TokenId.Eq && + if assign.Op.Id == token::Id.Eq && equalModels(assign.Left.Model, assign.Right.Model) { self.removeCurrent() self.i-- // In next iteration, point to correct statement. @@ -435,27 +435,27 @@ impl scopeOptimizer { exprOptimizer.optimizeData(assign.Right.Model, self.data) match assign.Op.Id { - | lex::TokenId.SolidusEq | lex::TokenId.PercentEq | lex::TokenId.ShlEq | lex::TokenId.ShrEq: + | token::Id.SolidusEq | token::Id.PercentEq | token::Id.ShlEq | token::Id.ShrEq: // Do not check structures. if !Math || assign.Left.Kind.Struct() != nil { break } oldId, oldKind := assign.Op.Id, assign.Op.Kind match assign.Op.Id { - | lex::TokenId.SolidusEq: - assign.Op.Id = lex::TokenId.Solidus - assign.Op.Kind = lex::TokenKind.Solidus - | lex::TokenId.PercentEq: - assign.Op.Id = lex::TokenId.Percent - assign.Op.Kind = lex::TokenKind.Percent - | lex::TokenId.ShlEq: - assign.Op.Id = lex::TokenId.Shl - assign.Op.Kind = lex::TokenKind.Shl - | lex::TokenId.ShrEq: - assign.Op.Id = lex::TokenId.Shr - assign.Op.Kind = lex::TokenKind.Shr + | token::Id.SolidusEq: + assign.Op.Id = token::Id.Solidus + assign.Op.Kind = token::Kind.Solidus + | token::Id.PercentEq: + assign.Op.Id = token::Id.Percent + assign.Op.Kind = token::Kind.Percent + | token::Id.ShlEq: + assign.Op.Id = token::Id.Shl + assign.Op.Kind = token::Kind.Shl + | token::Id.ShrEq: + assign.Op.Id = token::Id.Shr + assign.Op.Kind = token::Kind.Shr |: - panic("implementation mistake, this panic call should be unreachable") + panic("opt: implementation mistake, this panic call should be unreachable") } mut b := &sema::BinaryExprModel{ Op: assign.Op, @@ -468,9 +468,9 @@ impl scopeOptimizer { // Binary model optimized. // Use optimized model directly. assign.Right = new(sema::OperandExprModel, *assign.Right) - b.Op = new(lex::Token, *b.Op) // Unsafe model wraps original model. Save token. - assign.Op.Id = lex::TokenId.Eq - assign.Op.Kind = lex::TokenKind.Eq + b.Op = new(token::Token, *b.Op) // Unsafe model wraps original model. Save token. + assign.Op.Id = token::Id.Eq + assign.Op.Kind = token::Kind.Eq assign.Right.Model = model ret } @@ -672,7 +672,7 @@ fn isUnreachableExpr(&expr: sema::ExprModel): bool { ret c.IsBool() && !c.ReadBool() | &sema::BinaryExprModel: m := (&sema::BinaryExprModel)(expr) - if m.Op.Id == lex::TokenId.DblAmper { + if m.Op.Id == token::Id.DblAmper { ret isUnreachableExpr(m.Left.Model) || isUnreachableExpr(m.Right.Model) } diff --git a/src/julec/windows.jule b/src/julec/windows.jule index 72a73a5a6..b19b83712 100644 --- a/src/julec/windows.jule +++ b/src/julec/windows.jule @@ -4,7 +4,7 @@ #build windows -use sys for std::sys +use "std/sys" // When writing with WriteFile or WriteConsole, characters are parsed for VT100 // and similar control character sequences that control cursor movement, diff --git a/std/bytes/bytes.jule b/std/bytes/bytes.jule index d1290f2ca..4aeb8db2a 100644 --- a/std/bytes/bytes.jule +++ b/std/bytes/bytes.jule @@ -7,9 +7,9 @@ // But optimized for byte slices, may provide more efficient functions. // If you have byte slice form of strings, this package is the best option for most cases. -use unicode for std::unicode -use utf8 for std::unicode::utf8 -use fastbytes for std::internal::fastbytes +use "std/internal/fastbytes" +use "std/unicode" +use "std/unicode/utf8" // Returns bytes that equals to concatenation of n-count s. // Returns nil slice is n <= 0. @@ -18,7 +18,7 @@ fn Repeat(s: []byte, mut n: int): []byte { ret nil } if len(s) > int.Max/n { - panic("std::bytes: repeat: integer buffer size overflow") + panic("bytes: repeat: integer buffer size overflow") } mut buff := make([]byte, len(s)*n) diff --git a/std/conv/atof.jule b/std/conv/atof.jule index b8529af48..de74c438c 100644 --- a/std/conv/atof.jule +++ b/std/conv/atof.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use std::unsafe -use math for std::math +use "std/math" +use "std/unsafe" const optimize = true diff --git a/std/conv/eisel_lemire.jule b/std/conv/eisel_lemire.jule index f30e10d0c..b42497df3 100644 --- a/std/conv/eisel_lemire.jule +++ b/std/conv/eisel_lemire.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use math for std::math -use bits for std::math::bits +use "std/math" +use "std/math/bits" fn eiselLemire64(mut man: u64, exp10: int, neg: bool): (f: f64, ok: bool) { // The terse comments in this function body refer to sections of the diff --git a/std/conv/ftoa.jule b/std/conv/ftoa.jule index 42f659dea..77c27c5c5 100644 --- a/std/conv/ftoa.jule +++ b/std/conv/ftoa.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use std::unsafe -use math for std::math +use "std/math" +use "std/unsafe" struct floatInfo { mantbits: uint @@ -95,7 +95,7 @@ fn genericFtoa(mut dst: []byte, val: f64, fmt: byte, mut prec: int, bitSize: int bits = math::F64Bits(val) flt = unsafe { (&floatInfo)(&f64info) } |: - panic("std::conv: illegal bitSize") + panic("conv: illegal bitSize") } neg := bits>>(flt.expbits+flt.mantbits) != 0 diff --git a/std/conv/ftoaryu.jule b/std/conv/ftoaryu.jule index 4235c4671..949f720ec 100644 --- a/std/conv/ftoaryu.jule +++ b/std/conv/ftoaryu.jule @@ -35,7 +35,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use bits for std::math::bits +use "std/math/bits" // binary to decimal conversion using the RyÅ« algorithm. // @@ -48,10 +48,10 @@ use bits for std::math::bits // Formats mant*(2^exp) with prec decimal digits. fn ryuFtoaFixed32(mut &d: decimalSlice, mut mant: u32, exp: int, prec: int) { if prec < 0 { - panic("ryuFtoaFixed32 called with negative prec") + panic("conv: ryuFtoaFixed32 called with negative prec") } if prec > 9 { - panic("ryuFtoaFixed32 called with prec > 9") + panic("conv: ryuFtoaFixed32 called with prec > 9") } // Zero input. if mant == 0 { @@ -80,7 +80,7 @@ fn ryuFtoaFixed32(mut &d: decimalSlice, mut mant: u32, exp: int, prec: int) { mut di, dexp2, mut d0 := mult64bitPow10(mant, e2, q) if dexp2 >= 0 { - panic("not enough significant bits after mult64bitPow10") + panic("conv: not enough significant bits after mult64bitPow10") } // As a special case, computation might still be exact, if exponent // was negative and if it amounts to computing an exact division. @@ -120,7 +120,7 @@ fn ryuFtoaFixed32(mut &d: decimalSlice, mut mant: u32, exp: int, prec: int) { // Formats mant*(2^exp) with prec decimal digits. fn ryuFtoaFixed64(mut &d: decimalSlice, mut mant: u64, exp: int, prec: int) { if prec > 18 { - panic("ryuFtoaFixed64 called with prec > 18") + panic("conv: ryuFtoaFixed64 called with prec > 18") } // Zero input. if mant == 0 { @@ -152,7 +152,7 @@ fn ryuFtoaFixed64(mut &d: decimalSlice, mut mant: u64, exp: int, prec: int) { mut di, dexp2, mut d0 := mult128bitPow10(mant, e2, q) if dexp2 >= 0 { - panic("not enough significant bits after mult128bitPow10") + panic("conv: not enough significant bits after mult128bitPow10") } // As a special case, computation might still be exact, if exponent // was negative and if it amounts to computing an exact division. @@ -300,7 +300,7 @@ fn ryuFtoaShortest(mut &d: decimalSlice, mut mant: u64, exp: int, &flt: floatInf du, e2, du0 = mult128bitPow10(mu, e2, q) } if e2 >= 0 { - panic("not enough significant bits after mult128bitPow10") + panic("conv: not enough significant bits after mult128bitPow10") } // Is it an exact computation? if q > 55 { @@ -538,7 +538,7 @@ fn mult64bitPow10(m: u32, mut e2: int, q: int): (resM: u32, resE: int, exact: bo } if q < detailedPowsOfTenMinExp10 || detailedPowsOfTenMaxExp10 < q { // This never happens due to the range of f32/f64 exponent - panic("mult64bitPow10: power of 10 is out of range") + panic("conv: mult64bitPow10: power of 10 is out of range") } mut pow := detailedPowsOfTen[q-detailedPowsOfTenMinExp10][1] if q < 0 { @@ -566,7 +566,7 @@ fn mult128bitPow10(m: u64, mut e2: int, q: int): (resM: u64, resE: int, exact: b } if q < detailedPowsOfTenMinExp10 || detailedPowsOfTenMaxExp10 < q { // This never happens due to the range of f32/f64 exponent - panic("mult128bitPow10: power of 10 is out of range") + panic("conv: mult128bitPow10: power of 10 is out of range") } mut pow := detailedPowsOfTen[q-detailedPowsOfTenMinExp10] if q < 0 { diff --git a/std/conv/itoa.jule b/std/conv/itoa.jule index 60c987af2..5036c13de 100644 --- a/std/conv/itoa.jule +++ b/std/conv/itoa.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use std::unsafe -use bits for std::math::bits +use "std/math/bits" +use "std/unsafe" // enable fast path for small integers const fastSmalls = true @@ -104,7 +104,7 @@ fn isPowerOfTwo(x: int): bool { // as the second result value. fn fmtBits(mut dst: []byte, mut u: u64, base: int, neg: bool, append_: bool): (d: []byte, s: str) { if base < 2 || base > len(digits) { - panic("std::conv: illegal base") + panic("conv: illegal base") } // 2 <= base && base <= len(digits) diff --git a/std/encoding/ascii85/ascii85.jule b/std/encoding/ascii85/ascii85.jule index 8003dc8ca..fcb664cf1 100644 --- a/std/encoding/ascii85/ascii85.jule +++ b/std/encoding/ascii85/ascii85.jule @@ -35,7 +35,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use io for std::io +use "std/io" // Returns the maximum length of an encoding of n source bytes. fn MaxEncodeLen(n: int): int { diff --git a/std/encoding/ascii85/ascii85_test.jule b/std/encoding/ascii85/ascii85_test.jule index 2036c1580..ba7209039 100644 --- a/std/encoding/ascii85/ascii85_test.jule +++ b/std/encoding/ascii85/ascii85_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static encodeDecodeMap = [ [[]byte("BOu!rDdP(J/RN^?Ebo7"), []byte("hello_---_world")], diff --git a/std/encoding/base32/base32.jule b/std/encoding/base32/base32.jule index 65b932546..47e37b1dd 100644 --- a/std/encoding/base32/base32.jule +++ b/std/encoding/base32/base32.jule @@ -4,7 +4,7 @@ // TODO: add encoder and decoder functionality like [std::encoding::ascii85]. -use fastbytes for std::internal::fastbytes +use "std/internal/fastbytes" // Table for standard base32 encoding. static t32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" @@ -14,7 +14,8 @@ const paddingByte = '=' fn lenNoPad(b: []byte): int { mut i := len(b) - 1 - for i >= 0 && b[i] == paddingByte; i-- {} + for i >= 0 && b[i] == paddingByte; i-- { + } ret i + 1 } diff --git a/std/encoding/base32/base32_test.jule b/std/encoding/base32/base32_test.jule index b11e19137..a230ac75d 100644 --- a/std/encoding/base32/base32_test.jule +++ b/std/encoding/base32/base32_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static encodeDecodeMap = [ // RFC 4648 examples. @@ -65,7 +65,8 @@ fn testDecode(t: &testing::T) { fn removePad(b: []byte): []byte { mut bm := unsafe { *(&b) } mut i := len(b) - 1 - for i >= 0 && b[i] == paddingByte; i-- {} + for i >= 0 && b[i] == paddingByte; i-- { + } ret bm[:i+1] } diff --git a/std/encoding/base64/base64_test.jule b/std/encoding/base64/base64_test.jule index 74d9d85c9..c963e3959 100644 --- a/std/encoding/base64/base64_test.jule +++ b/std/encoding/base64/base64_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static encodeDecodeMap = [ // RFC 3548 examples. @@ -70,7 +70,8 @@ fn testDecode(t: &testing::T) { fn removePad(b: []byte): []byte { mut bm := unsafe { *(&b) } mut i := len(b) - 1 - for i >= 0 && b[i] == paddingByte; i-- {} + for i >= 0 && b[i] == paddingByte; i-- { + } ret bm[:i+1] } diff --git a/std/encoding/binary/big_endian.jule b/std/encoding/binary/big_endian.jule index 31be0f439..5b48196ba 100644 --- a/std/encoding/binary/big_endian.jule +++ b/std/encoding/binary/big_endian.jule @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Binary encoding implementation for big-endian order. -struct BigEndian {} +struct BigEndian{} impl BigEndian { // Encodes unsigned 16-bit integer into 2-bytes slice. diff --git a/std/encoding/binary/little_endian.jule b/std/encoding/binary/little_endian.jule index a3966c37a..e347c5d00 100644 --- a/std/encoding/binary/little_endian.jule +++ b/std/encoding/binary/little_endian.jule @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Binary encoding implementation for little-endian order. -struct LittleEndian {} +struct LittleEndian{} impl LittleEndian { // Encodes unsigned 16-bit integer into 2-bytes slice. diff --git a/std/encoding/csv/error.jule b/std/encoding/csv/error.jule index 4a0819e7e..dfb87b83f 100644 --- a/std/encoding/csv/error.jule +++ b/std/encoding/csv/error.jule @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // CSV error codes. -enum CsvError { +enum Error { Read, FieldCount, InvalidDelim, @@ -14,8 +14,8 @@ enum CsvError { // A ParseError is returned for parsing errors. // Line and column numbers are 1-indexed. struct ParseError { - StartLine: int // Line where the record starts - Line: int // Line where the error occurred - Column: int // Column (1-based byte index) where the error occurred - Err: CsvError // The actual error + StartLine: int // Line where the record starts + Line: int // Line where the error occurred + Column: int // Column (1-based byte index) where the error occurred + Err: Error // The actual error } \ No newline at end of file diff --git a/std/encoding/csv/reader.jule b/std/encoding/csv/reader.jule index 814841f33..d67290130 100644 --- a/std/encoding/csv/reader.jule +++ b/std/encoding/csv/reader.jule @@ -83,10 +83,10 @@ // {`Multi-line // field`, `comma is ,`} -use bytes for std::bytes -use io for std::io -use unicode for std::unicode -use utf8 for std::unicode::utf8 +use "std/bytes" +use "std/io" +use "std/unicode" +use "std/unicode/utf8" // Holds the position of a field in the current line. struct position { @@ -165,7 +165,7 @@ struct Reader { // last record returned by Read. fieldPositions: []position - // Record cache and only used when reuse_record == true. + // Record cache and only used when ReuseRecord == true. lastRecord: []str } @@ -187,11 +187,11 @@ impl Reader { // Reads one record (a slice of fields) from r. // If the record has an unexpected number of fields, - // read returns the [CsvError.FieldCount] as exception. + // read returns the [Error.FieldCount] as exception. // If there is no data left to be read, read returns nil. // If [self.ReuseRecord] is true, the returned slice may be shared // between multiple calls to read. - // Exception can be CsvError or ParseError, and forwards reader's exceptions. + // Exception can be Error or ParseError, and forwards reader's exceptions. fn Read(mut self)!: (record: []str) { if self.ReuseRecord { record = self.readRecord(self.lastRecord) else { error(error) } @@ -210,7 +210,7 @@ impl Reader { // If this is called with an out-of-bounds index, it panics. fn FieldPos(self, field: int): (line: int, column: int) { if field < 0 || field >= len(self.fieldPositions) { - panic("std::encoding::csv: Reader: out of range index passed to field_pos") + panic("csv: Reader: out of range index passed to field_pos") } p := &self.fieldPositions[field] unsafe { @@ -220,7 +220,7 @@ impl Reader { // Reads all the remaining records from r. // Each record is a slice of fields. - // Exception can be CsvError or ParseError, and forwards reader errors. + // Exception can be Error or ParseError, and forwards reader errors. fn ReadAll(mut self)!: (records: [][]str) { for { mut record := self.readRecord(nil) else { error(error) } @@ -259,7 +259,7 @@ impl Reader { if self.Comma == self.Comment || !validDelim(self.Comma) || (self.Comment != 0 && !validDelim(self.Comment)) { - error(CsvError.InvalidDelim) + error(Error.InvalidDelim) } // Read line (automatically skipping past empty lines and any comments). @@ -318,7 +318,7 @@ impl Reader { StartLine: recLine, Line: self.numLine, Column: pos.col + j, - Err: CsvError.BareQuote, + Err: Error.BareQuote, }) break parseField } @@ -372,7 +372,7 @@ impl Reader { StartLine: recLine, Line: self.numLine, Column: pos.col - QuoteLen, - Err: CsvError.Quote, + Err: Error.Quote, }) break parseField } @@ -392,7 +392,7 @@ impl Reader { StartLine: recLine, Line: pos.line, Column: pos.col, - Err: CsvError.Quote, + Err: Error.Quote, }) break parseField } @@ -425,7 +425,7 @@ impl Reader { StartLine: recLine, Line: recLine, Column: 1, - Err: CsvError.FieldCount, + Err: Error.FieldCount, }) } } else if self.FieldsPerRecord == 0 { diff --git a/std/encoding/csv/writer.jule b/std/encoding/csv/writer.jule index d0837a042..d466e78dc 100644 --- a/std/encoding/csv/writer.jule +++ b/std/encoding/csv/writer.jule @@ -35,11 +35,11 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use std::unsafe -use io for std::io -use bytes for std::bytes -use unicode for std::unicode -use utf8 for std::unicode::utf8 +use "std/bytes" +use "std/io" +use "std/unicode" +use "std/unicode/utf8" +use "std/unsafe" // A Writer writes records using CSV encoding. // @@ -111,7 +111,7 @@ impl Writer { // Forwards any exceptional from internal objects such as writer. fn Write(mut self, record: []str)! { if !validDelim(self.Comma) { - error(CsvError.InvalidDelim) + error(Error.InvalidDelim) } for (n, mut field) in record { if n > 0 { diff --git a/std/encoding/json/buffer.jule b/std/encoding/json/buffer.jule index 2b7515991..0c9b02932 100644 --- a/std/encoding/json/buffer.jule +++ b/std/encoding/json/buffer.jule @@ -59,7 +59,7 @@ impl buffer { // don't spend all our time copying. copy(self.buf, self.buf[self.off:]) } else if c > int.Max-c-n { - panic("buffer too large") + panic("json: buffer too large") } else { // Add self.off to account for self.buf[:self.off] being sliced off the front. self.buf = growSlice(self.buf[self.off:], self.off+n) diff --git a/std/encoding/json/decode.jule b/std/encoding/json/decode.jule index ee2f1a2ec..81ff751b8 100644 --- a/std/encoding/json/decode.jule +++ b/std/encoding/json/decode.jule @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use base64 for std::encoding::base64 -use conv for std::conv -use comptime for std::comptime -use unicode for std::unicode -use utf8 for std::unicode::utf8 -use utf16 for std::unicode::utf16 +use "std/comptime" +use "std/conv" +use "std/encoding/base64" +use "std/unicode" +use "std/unicode/utf16" +use "std/unicode/utf8" +use "std/unsafe" // This limits the max nesting depth to prevent stack overflow. // This is permitted by https://tools.ietf.org/html/rfc7159#section-9 @@ -37,7 +37,8 @@ impl jsonDecoder { } fn skipSpace(self) { - for !self.eof() && isSpace(self.data[self.i]); self.i++ {} + for !self.eof() && isSpace(self.data[self.i]); self.i++ { + } } // Scans to the end of what was started. @@ -65,7 +66,7 @@ impl jsonDecoder { self.i++ | '}': if colon || self.parseState[len(self.parseState)-1] != parseState.Object { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } self.popParseState() self.i++ @@ -74,7 +75,7 @@ impl jsonDecoder { } | ']': if colon || self.parseState[len(self.parseState)-1] != parseState.Array { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.popParseState() self.i++ @@ -83,59 +84,59 @@ impl jsonDecoder { } | ':': if colon { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } if self.parseState[len(self.parseState)-1] != parseState.Object { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } if len(self.data)-self.i <= 1 || self.data[self.i-1] != '"' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.i++ colon = true continue | ',': if colon { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.i++ self.skipSpace() if self.parseState[len(self.parseState)-1] == parseState.Object { if self.eof() || self.data[self.i] != '"' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.scanValidLit() else { error(error) } self.skipSpace() if self.eof() || self.data[self.i] != ':' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.i++ colon = true continue } if self.eof() { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } b = self.data[self.i] if b == ',' || b == ':' || b == '}' || b == ']' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } | '-' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '"' | 't' | 'f' | 'n': self.scanValidLit() else { error(error) } |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } colon = false } - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } // Calls the [scanLit] and checks it with the [isValidLit] function. fn scanValidLit(self)!: []byte { mut lit := self.scanLit() else { error(error) } if !isValidLit(lit) { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } ret lit } @@ -175,10 +176,10 @@ impl jsonDecoder { | 'n': // null self.i += len("null") |: - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } if self.i > len(self.data) { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } // Keep immutability, it will not be mutated. ret unsafe { (*(&self.data))[i:self.i] } @@ -189,7 +190,7 @@ impl jsonDecoder { fn pushParseState(self, newParseState: parseState)! { self.parseState = append(self.parseState, newParseState) if len(self.parseState) > maxNestingDepth { - error(JSONDecodeError.ExceededMaxDepth) + error(DecodeError.ExceededMaxDepth) } } @@ -218,13 +219,13 @@ impl jsonDecoder { // Look ahead for ] - can only happen on first iteration. self.skipSpace() if self.eof() { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } const match t.Kind() { | comptime::Kind.Array: if i >= len(a) { // Ran out of fixed array. - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } self.value(a[i]) else { error(error) } | comptime::Kind.Slice: @@ -232,12 +233,12 @@ impl jsonDecoder { self.value(v) else { error(error) } a = append(a, v) |: - panic("std::encoding::json: unimplemented type, this panic call should be unreachable") + panic("json: unimplemented type, this panic call should be unreachable") } i++ self.skipSpace() if self.eof() { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } // Next token must be , or ]. b := self.data[self.i] @@ -249,7 +250,7 @@ impl jsonDecoder { self.i++ break } - panic("std::encoding::json: implementation mistake, this panic call should be unreachable") + panic("json: implementation mistake, this panic call should be unreachable") } self.popParseState() if i < len(a) { @@ -264,7 +265,7 @@ impl jsonDecoder { // Truncate the slice. a = a[:i] |: - panic("std::encoding::json: unimplemented type, this panic call should be unreachable") + panic("json: unimplemented type, this panic call should be unreachable") } } } @@ -275,7 +276,7 @@ impl jsonDecoder { | str | int | i8 | i16 | i32 | i64 | uint | uintptr | u8 | u16 | u32 | u64: break |: - error(JSONEncodeError.UnsupportedType) + error(EncodeError.UnsupportedType) } self.i++ if !self.eof() && self.data[self.i] == '}' { @@ -287,18 +288,18 @@ impl jsonDecoder { for { self.skipSpace() if self.eof() || self.data[self.i] != '"' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } // Don't check validity for literal, following algorithms will check it. lit := self.scanLit() else { error(error) } self.skipSpace() if self.eof() || self.data[self.i] != ':' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.i++ self.skipSpace() if self.eof() { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } let mut value: V self.value(value) else { error(error) } @@ -316,7 +317,7 @@ impl jsonDecoder { // Quoted non-string type, parse unqoted value by type to assign. key := unquoteBytes(lit) if key == nil { - panic("std::encoding::json: implementation mistake, this panic call should be unreachable") + panic("json: implementation mistake, this panic call should be unreachable") } let mut keyV: K const match type K { @@ -325,7 +326,7 @@ impl jsonDecoder { | uint | uintptr | u8 | u16 | u32 | u64: decodeUint(keyV, key) else { error(error) } |: - panic("std::encoding::json: unimplemented type, this panic call should be unreachable") + panic("json: unimplemented type, this panic call should be unreachable") } if m == nil { m = {} // create new map @@ -334,7 +335,7 @@ impl jsonDecoder { } self.skipSpace() if self.eof() { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } b := self.data[self.i] if b == ',' { @@ -345,7 +346,7 @@ impl jsonDecoder { self.i++ break } - panic("std::encoding::json: implementation mistake, this panic call should be unreachable") + panic("json: implementation mistake, this panic call should be unreachable") } self.popParseState() } @@ -361,22 +362,22 @@ impl jsonDecoder { for { self.skipSpace() if self.eof() || self.data[self.i] != '"' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } // Don't check validity for literal, following algorithms will check it. lit := self.scanLit() else { error(error) } self.skipSpace() if self.eof() || self.data[self.i] != ':' { - error(JSONDecodeError.InvalidToken) + error(DecodeError.InvalidToken) } self.i++ self.skipSpace() if self.eof() { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } key := unquoteBytes(lit) if key == nil { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } keyS := unsafe::BytesStr(key) // To avoid unused error. @@ -404,7 +405,7 @@ impl jsonDecoder { fieldDecoded: self.skipSpace() if self.eof() { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } b := self.data[self.i] if b == ',' { @@ -415,7 +416,7 @@ impl jsonDecoder { self.i++ break } - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } self.popParseState() } @@ -433,7 +434,7 @@ impl jsonDecoder { self.objectStruct(t) else { error(error) } ret |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } | '[': // Array. const match tt.Kind() { @@ -442,7 +443,7 @@ impl jsonDecoder { self.array(t) else { error(error) } ret |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } | '"': // String literal. const match type T { @@ -455,12 +456,12 @@ impl jsonDecoder { lit := self.scanLit() else { error(error) } mut s2 := unquoteBytes(lit) if s2 == nil { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } t = base64::Decode(s2) ret |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } | 'n': // Null literal. self.scanValidLit() else { error(error) } @@ -469,7 +470,7 @@ impl jsonDecoder { t = nil ret |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } | 't' | 'f': // Boolean literal. self.scanValidLit() else { error(error) } @@ -478,7 +479,7 @@ impl jsonDecoder { t = b == 't' ret |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } } if b == '-' || b == '0' || '1' <= b && b <= '9' { @@ -496,10 +497,10 @@ impl jsonDecoder { decodeFloat(t, lit) else { error(error) } ret |: - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } } - error(JSONDecodeError.MissingBeginningOfValue) + error(DecodeError.MissingBeginningOfValue) } fn value[T](self, mut &t: T)! { @@ -528,7 +529,7 @@ impl jsonDecoder { self.value(t) else { error(error) } } if len(self.data)-self.i > 0 { - error(JSONDecodeError.UnexpectedEnd) + error(DecodeError.UnexpectedEnd) } } } @@ -544,9 +545,9 @@ impl jsonDecoder { // Decoding details: // Since this function designed for comptime type analysis, the type [T] should // be valid type for comptime. The type [any], which is stores dynamic type, is not valid. -// Any unsupported type causes exceptional with [JSONDecodeError.UnsupportedType]. +// Any unsupported type causes exceptional with [DecodeError.UnsupportedType]. // Any incompatible value for type, invalid literal or something else causes -// exceptional with [JSONDecodeError.UnsupportedType]. +// exceptional with [DecodeError.UnsupportedType]. // // Signed/Unsigned Integers, Floating-Points: // Decode as JSON numbers. @@ -575,7 +576,7 @@ impl jsonDecoder { // Maps: // Decode as JSON object. // Map's key type only can be: signed integer, unsigned integer and string. -// Other types will cause exceptional with [JSONDecodeError.UnsupportedType]. +// Other types will cause exceptional with [DecodeError.UnsupportedType]. // // Smart Pointers: // If smart pointer is nil, will be allocated by the algorithm for decoding. @@ -738,9 +739,9 @@ fn unquoteBytes(s: []byte): (t: []byte) { fn decodeInt[T](mut &t: T, lit: []byte)! { // Use [unsafe::ByteStr] instead of casting. // The byte buffer will not change, so it's safe and efficient. - n := conv::ParseInt(unsafe::BytesStr(lit), 0xA, 1<<6) else { error(JSONDecodeError.InvalidValue) } + n := conv::ParseInt(unsafe::BytesStr(lit), 0xA, 1<<6) else { error(DecodeError.InvalidValue) } if n < i64(T.Min) || i64(T.Max) < n { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } t = (T)(n) } @@ -748,9 +749,9 @@ fn decodeInt[T](mut &t: T, lit: []byte)! { fn decodeUInt[T](mut &t: T, lit: []byte)! { // Use [unsafe::ByteStr] instead of casting. // The byte buffer will not change, so it's safe and efficient. - n := conv::ParseUint(unsafe::BytesStr(lit), 0xA, 1<<6) else { error(JSONDecodeError.InvalidValue) } + n := conv::ParseUint(unsafe::BytesStr(lit), 0xA, 1<<6) else { error(DecodeError.InvalidValue) } if u64(T.Max) < n { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } t = (T)(n) } @@ -758,9 +759,9 @@ fn decodeUInt[T](mut &t: T, lit: []byte)! { fn decodeFloat[T](mut &t: T, lit: []byte)! { // Use [unsafe::ByteStr] instead of casting. // The byte buffer will not change, so it's safe and efficient. - n := conv::ParseFloat(unsafe::BytesStr(lit), 1<<6) else { error(JSONDecodeError.InvalidValue) } + n := conv::ParseFloat(unsafe::BytesStr(lit), 1<<6) else { error(DecodeError.InvalidValue) } if f64(T.Max) < n { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } t = (T)(n) } @@ -768,7 +769,7 @@ fn decodeFloat[T](mut &t: T, lit: []byte)! { fn decodeString(mut &s: str, lit: []byte)! { mut s2 := unquoteBytes(lit) if s2 == nil { - error(JSONDecodeError.InvalidValue) + error(DecodeError.InvalidValue) } if len(s2) == 0 { s = "" diff --git a/std/encoding/json/decode_test.jule b/std/encoding/json/decode_test.jule index c874fd46e..d35d0bd98 100644 --- a/std/encoding/json/decode_test.jule +++ b/std/encoding/json/decode_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" #test fn testDecodeStr(t: &testing::T) { diff --git a/std/encoding/json/encode.jule b/std/encoding/json/encode.jule index 47a96938d..c0e87e426 100644 --- a/std/encoding/json/encode.jule +++ b/std/encoding/json/encode.jule @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use base64 for std::encoding::base64 -use conv for std::conv -use comptime for std::comptime -use math for std::math -use utf8 for std::unicode::utf8 +use "std/comptime" +use "std/conv" +use "std/encoding/base64" +use "std/math" +use "std/unicode/utf8" +use "std/unsafe" const hex = "0123456789abcdef" @@ -79,7 +79,7 @@ impl jsonEncoder { fn encodeFloat(mut self, f: f64, bits: int)! { if math::IsNaN(f) || math::IsInf(f, 0) { - error(JSONEncodeError.UnsupportedFloatValue) + error(EncodeError.UnsupportedFloatValue) } mut fmt := 'f' abs := math::Abs(f) @@ -245,7 +245,7 @@ impl jsonEncoder { | comptime::Kind.U64: break |: - error(JSONEncodeError.UnsupportedType) + error(EncodeError.UnsupportedType) } if t == nil { self.encodeNil() @@ -350,7 +350,7 @@ impl jsonEncoder { const tt = comptime::TypeOf(T) const match { | tt.Binded(): - error(JSONEncodeError.UnsupportedType) + error(EncodeError.UnsupportedType) } const match type T { | int | i8 | i16 | i32 | i64: @@ -392,7 +392,7 @@ impl jsonEncoder { | comptime::Kind.Slice: self.encodeSlice[T, Flag](t) else { error(error) } |: - error(JSONEncodeError.UnsupportedType) + error(EncodeError.UnsupportedType) } } } @@ -417,11 +417,11 @@ fn encoder(): jsonEncoder { // Encoding details: // Since this function designed for comptime type analysis, the type [T] should // be valid type for comptime. The type [any], which is stores dynamic type, is not valid. -// Any unsupported type causes exceptional with [JSONEncodeError.UnsupportedType]. +// Any unsupported type causes exceptional with [EncodeError.UnsupportedType]. // // Signed/Unsigned Integers, Floating-Points: // Encode as JSON numbers. -// For floating-points, NaN or ±Inf will cause exceptional with [JSONEncodeError.UnsupportedFloatValue]. +// For floating-points, NaN or ±Inf will cause exceptional with [EncodeError.UnsupportedFloatValue]. // // Booleans: // Encode as JSON booleans. @@ -449,7 +449,7 @@ fn encoder(): jsonEncoder { // If map is nil, encode as null JSON value. // The keys of the map always will be quoted. // Also map's key type only can be: signed integer, unsigned integer and string. -// Other types will cause exceptional with [JSONEncodeError.UnsupportedType]. +// Other types will cause exceptional with [EncodeError.UnsupportedType]. // // Smart Pointers: // If smart pointer is nil, encode as null JSON value. diff --git a/std/encoding/json/encode_test.jule b/std/encoding/json/encode_test.jule index 3bc8ad970..16f0f6ab2 100644 --- a/std/encoding/json/encode_test.jule +++ b/std/encoding/json/encode_test.jule @@ -4,8 +4,8 @@ #build test -use testing for std::testing -use base64 for std::encoding::base64 +use "std/encoding/base64" +use "std/testing" fn encodeMapXKey[Map](t: &testing::T, m: Map, kind: str) { bytes := Encode(m) else { diff --git a/std/encoding/json/error.jule b/std/encoding/json/error.jule index 9a42ccbd1..f30b24c5e 100755 --- a/std/encoding/json/error.jule +++ b/std/encoding/json/error.jule @@ -3,13 +3,13 @@ // license that can be found in the LICENSE file. // JSON encoding error codes. -enum JSONEncodeError { +enum EncodeError { UnsupportedType, UnsupportedFloatValue, // NaN or ±Inf } // JSON decoding error codes. -enum JSONDecodeError { +enum DecodeError { UnsupportedType, UnexpectedEnd, // Unexpected end of JSON input. ExceededMaxDepth, diff --git a/std/encoding/json/validate_test.jule b/std/encoding/json/validate_test.jule index e8a1eea58..8001a9099 100644 --- a/std/encoding/json/validate_test.jule +++ b/std/encoding/json/validate_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" struct validCase { data: str diff --git a/std/env/error.jule b/std/env/error.jule index e3a0a148f..44b5a7ba5 100644 --- a/std/env/error.jule +++ b/std/env/error.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" // Env error codes. -enum EnvError { +enum Error { Denied, // Search permission is denied for a component of the path prefix IO, // Input/Output error, an error occurred while reading from the file system Loop, // A loop exists in symbolic links encountered during resolution of the path argument @@ -17,24 +17,24 @@ enum EnvError { } // Returns last os error by errno. -fn getLastOsError(): EnvError { +fn getLastOsError(): Error { err := sys::GetLastErrno() match err { | sys::EACCES: - ret EnvError.Denied + ret Error.Denied | sys::EIO: - ret EnvError.IO + ret Error.IO | sys::ELOOP: - ret EnvError.Loop + ret Error.Loop | sys::ENAMETOOLONG: - ret EnvError.LongPath + ret Error.LongPath | sys::ENOENT: - ret EnvError.NotExist + ret Error.NotExist | sys::ENOTDIR: - ret EnvError.NotDir + ret Error.NotDir | sys::ENOMEM: - ret EnvError.InsufficientMemory + ret Error.InsufficientMemory |: - ret EnvError.IO + ret Error.IO } } \ No newline at end of file diff --git a/std/env/error_windows.jule b/std/env/error_windows.jule index 29e268e28..4f6656351 100644 --- a/std/env/error_windows.jule +++ b/std/env/error_windows.jule @@ -2,21 +2,21 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" // Returns last os error by error number of windows. -fn getLastOsErrorWindows(): EnvError { +fn getLastOsErrorWindows(): Error { err := sys::GetLastError() match err { | sys::ERROR_ACCESS_DENIED: - ret EnvError.Denied + ret Error.Denied | sys::ERROR_PATH_NOT_FOUND: - ret EnvError.NotExist + ret Error.NotExist | sys::ERROR_NOT_READY: - ret EnvError.Device + ret Error.Device | sys::ERROR_INVALID_NAME: - ret EnvError.NotExist + ret Error.NotExist |: - ret EnvError.Denied + ret Error.Denied } } \ No newline at end of file diff --git a/std/env/proc.jule b/std/env/proc.jule index f4eac3945..4cd75544f 100644 --- a/std/env/proc.jule +++ b/std/env/proc.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use runtime for std::runtime +use "std/runtime" // Returns command-line arguments. // Starts with the program name. @@ -31,7 +31,7 @@ fn WorkingDir()!: str { // Device fn SetWorkingDir(path: str)! { if path == "" { - error(EnvError.NotDir) + error(Error.NotDir) } chdir(path) else { error(error) } } \ No newline at end of file diff --git a/std/env/proc_unix.jule b/std/env/proc_unix.jule index f6d1fd93c..7893adcdd 100644 --- a/std/env/proc_unix.jule +++ b/std/env/proc_unix.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use sys for std::sys +use integ "std/jule/integrated" +use "std/sys" // Possible errors: // Denied diff --git a/std/env/proc_windows.jule b/std/env/proc_windows.jule index 868ec48ad..3ebcc416e 100644 --- a/std/env/proc_windows.jule +++ b/std/env/proc_windows.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use sys for std::sys +use integ "std/jule/integrated" +use "std/sys" // Possible errors: // Denied diff --git a/std/flag/flag.jule b/std/flag/flag.jule index cb706165b..982d5ca0d 100644 --- a/std/flag/flag.jule +++ b/std/flag/flag.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use conv for std::conv -use strings for std::strings +use "std/conv" +use "std/strings" const bitSize = 0b1000000 @@ -130,11 +130,11 @@ impl FlagSet { fn addFlagCommon[T](mut self, name: str, short: rune, what: str): &Flag[T] { if self.FindFlag(name) != nil { - panic("std::flag: FlagSet.Add[T]: flag is already exist in this name: " + name) + panic("flag: FlagSet.Add[T]: flag is already exist in this name: " + name) } if short != 0 && self.FindFlagShort(short) != nil { - panic("std::flag: FlagSet.Add[T]: flag is already exist in this short name: " + str(short)) + panic("flag: FlagSet.Add[T]: flag is already exist in this short name: " + str(short)) } mut flag := &Flag[T]{ @@ -166,7 +166,7 @@ impl FlagSet { // Same with add method but do not allocates new reference, uses existing. fn AddVar[T: i64 | u64 | f64 | bool | str](mut self, mut var: &T, name: str, short: rune, what: str) { if var == nil { - panic("std::flag: FlatSet.AddVar[T]: variable is nil") + panic("flag: FlatSet.AddVar[T]: variable is nil") } mut flag := self.addFlagCommon[T](name, short, what) flag.default = *var diff --git a/std/fmt/format.jule b/std/fmt/format.jule index 375a98351..0e0dfa370 100644 --- a/std/fmt/format.jule +++ b/std/fmt/format.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fmt for std::internal::fmt +use "std/internal/fmt" +use "std/unsafe" // It places the passes arguments in the string relative to the corresponding // format string. Returns format string if len(args) == 0. If the arguments diff --git a/std/fmt/print.jule b/std/fmt/print.jule index eea9a0ea9..cd0f91603 100644 --- a/std/fmt/print.jule +++ b/std/fmt/print.jule @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fs for std::fs -use io for std::io -use fmt for std::internal::fmt -use strings for std::internal::strings +use "std/fs" +use "std/internal/fmt" +use "std/internal/strings" +use "std/io" +use "std/unsafe" // Prints arguments to file by default formatting. // See documentation of format function for formatting. fn Fprint(mut f: &fs::File, args: ...any) { - mut sb := strings::StrBuilder.New(20) + mut sb := strings::Builder.New(20) for _, arg in args { fmt::FmtByDefault(sb, arg) f.Write(unsafe { sb.Buf() }) else { - panic("std::fmt: Fprint: error occurs when printing") + panic("fmt: Fprint: error occurs when printing") } // Do not use the [Clear] method to avoid making new allocations. // The buffer used temporarily, so just clear the length, not capacity. @@ -36,7 +36,7 @@ fn Fprintln(mut f: &fs::File, args: ...any) { fn Fprintf(mut f: &fs::File, fmt: str, args: ...any) { format := fmt::Format(fmt, args...) f.Write(format) else { - panic("std::fmt: Fprintf: error occurs when printing") + panic("fmt: Fprintf: error occurs when printing") } } @@ -59,7 +59,7 @@ fn Println(args: ...any) { // Returns string result of arguments by default formatting. fn Sprint(args: ...any): str { - mut buf := strings::StrBuilder.New(100) + mut buf := strings::Builder.New(100) for _, arg in args { fmt::FmtByDefault(buf, arg) } diff --git a/std/fs/dir.jule b/std/fs/dir.jule index 60ea7a2f7..ea24a896d 100644 --- a/std/fs/dir.jule +++ b/std/fs/dir.jule @@ -9,4 +9,4 @@ struct DirEntry { } // Directory. -struct Directory {} \ No newline at end of file +struct Directory{} \ No newline at end of file diff --git a/std/fs/dir_unix.jule b/std/fs/dir_unix.jule index 5496a4602..bdcb4ffe9 100644 --- a/std/fs/dir_unix.jule +++ b/std/fs/dir_unix.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path -use integ for std::jule::integrated -use sys for std::sys +use "std/fs/path" +use integ "std/jule/integrated" +use "std/sys" impl Directory { // Reads the named directory and returs all its directory entries can read. diff --git a/std/fs/dir_windows.jule b/std/fs/dir_windows.jule index 5c6af48e0..c1837f559 100644 --- a/std/fs/dir_windows.jule +++ b/std/fs/dir_windows.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path -use integ for std::jule::integrated -use sys for std::sys +use "std/fs/path" +use integ "std/jule/integrated" +use "std/sys" impl Directory { // Reads the named directory and returs all its directory entries can read. @@ -42,7 +42,7 @@ impl Directory { // Make sure this situation should documented or not. utf16Path := integ::UTF16FromStr(path) - if unsafe { !std::sys::CreateDirectory(&utf16Path[0]) } { + if unsafe { !sys::CreateDirectory(&utf16Path[0]) } { error(getLastFsError()) } } @@ -52,7 +52,7 @@ impl Directory { // Possible errors: Denined NotExist NotEmpty SyncIO IO Loop NotDir static fn Remove(path: str)! { utf16Path := integ::UTF16FromStr(path) - if unsafe { !std::sys::RemoveDirectory(&utf16Path[0]) } { + if unsafe { !sys::RemoveDirectory(&utf16Path[0]) } { error(getLastFsError()) } } diff --git a/std/fs/error.jule b/std/fs/error.jule index 5dc7cc472..600197937 100644 --- a/std/fs/error.jule +++ b/std/fs/error.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" // File system error codes. -enum FsError { +enum Error { Denied, // Search permission is denied for a component of the path prefix IO, // Input/Output error, an error occurred while reading from the file system Loop, // A loop exists in symbolic links encountered during resolution of the path argument @@ -37,66 +37,66 @@ enum FsError { } // Returns last filesystem error by errno. -fn getLastFsError(): FsError { +fn getLastFsError(): Error { err := sys::GetLastErrno() match err { | sys::EACCES: - ret FsError.Denied + ret Error.Denied | sys::EIO: - ret FsError.IO + ret Error.IO | sys::ELOOP: - ret FsError.Loop + ret Error.Loop | sys::ENAMETOOLONG: - ret FsError.LongPath + ret Error.LongPath | sys::ENOENT: - ret FsError.NotExist + ret Error.NotExist | sys::ENOTDIR: - ret FsError.NotDir + ret Error.NotDir | sys::EOVERFLOW: - ret FsError.Overflow + ret Error.Overflow | sys::EBADF: - ret FsError.InvalidDescriptor + ret Error.InvalidDescriptor | sys::EMFILE: - ret FsError.PerProcessLimit + ret Error.PerProcessLimit | sys::ENFILE: - ret FsError.SystemWideLimit + ret Error.SystemWideLimit | sys::ENOMEM: - ret FsError.InsufficientMemory + ret Error.InsufficientMemory | sys::EEXIST: - ret FsError.Exist + ret Error.Exist | sys::EINTR: - ret FsError.Signal + ret Error.Signal | sys::EINVAL: - ret FsError.SyncIO + ret Error.SyncIO | sys::EISDIR: - ret FsError.IsDir + ret Error.IsDir | sys::ENOSR: - ret FsError.UnableStream + ret Error.UnableStream | sys::ENOSPC: - ret FsError.NoSpace + ret Error.NoSpace | sys::ENXIO: - ret FsError.Device + ret Error.Device | sys::EROFS: - ret FsError.ReadOnly + ret Error.ReadOnly | sys::EAGAIN: - ret FsError.Retry + ret Error.Retry | sys::ETXTBSY | sys::EBUSY: - ret FsError.Busy + ret Error.Busy | sys::EFBIG: - ret FsError.Big + ret Error.Big | sys::EPIPE: - ret FsError.Pipe + ret Error.Pipe | sys::ERANGE: - ret FsError.Range + ret Error.Range | sys::ESPIPE: - ret FsError.Seek + ret Error.Seek | sys::ENOBUFS: - ret FsError.Buffer + ret Error.Buffer | sys::EBADMSG: - ret FsError.BadMessage + ret Error.BadMessage | sys::ENOTEMPTY: - ret FsError.NotEmpty + ret Error.NotEmpty |: - ret FsError.IO + ret Error.IO } } \ No newline at end of file diff --git a/std/fs/file.jule b/std/fs/file.jule index 38a9f4070..9b8244566 100644 --- a/std/fs/file.jule +++ b/std/fs/file.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integrated for std::jule::integrated -use sys for std::sys +use "std/jule/integrated" +use "std/sys" // Seek whence values. enum Seek: int { @@ -67,7 +67,7 @@ impl File { static fn Read(path: str)!: []byte { s := Status.Of(path) else { error(error) } if !s.IsReg() { - error(FsError.IsDir) + error(Error.IsDir) } mut sz := int(s.Size()) diff --git a/std/fs/file_unix.jule b/std/fs/file_unix.jule index ef48243c5..b9988fae1 100644 --- a/std/fs/file_unix.jule +++ b/std/fs/file_unix.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use sys for std::sys -use runtime for std::runtime +use integ "std/jule/integrated" +use "std/runtime" +use "std/sys" impl File { // Opens file stream with named file, specified flag diff --git a/std/fs/file_windows.jule b/std/fs/file_windows.jule index 39c5f6988..a69e3fe5a 100644 --- a/std/fs/file_windows.jule +++ b/std/fs/file_windows.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use sys for std::sys -use utf8 for std::unicode::utf8 -use utf16 for std::unicode::utf16 -use runtime for std::runtime +use integ "std/jule/integrated" +use "std/runtime" +use "std/sys" +use "std/unicode/utf16" +use "std/unicode/utf8" impl File { // Opens file stream with named file, specified flag diff --git a/std/fs/path/path.jule b/std/fs/path/path.jule index d6106be19..66cd69139 100644 --- a/std/fs/path/path.jule +++ b/std/fs/path/path.jule @@ -35,9 +35,9 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use std::unsafe -use env for std::env -use strings for std::strings +use "std/env" +use "std/strings" +use "std/unsafe" // A LazyBuff is a lazily constructed path buffer. // It supports append, reading previously appended bytes, diff --git a/std/fs/path/path_unix.jule b/std/fs/path/path_unix.jule index 90245ce72..77a39cd73 100644 --- a/std/fs/path/path_unix.jule +++ b/std/fs/path/path_unix.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use env for std::env -use strings for std::strings +use "std/env" +use "std/strings" // Operating system specific path separator. const Separator = '/' diff --git a/std/fs/path/path_windows.jule b/std/fs/path/path_windows.jule index 3fdf78313..639f40856 100644 --- a/std/fs/path/path_windows.jule +++ b/std/fs/path/path_windows.jule @@ -35,9 +35,9 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use integ for std::jule::integrated -use strings for std::internal::strings -use sys for std::sys +use "std/internal/strings" +use integ "std/jule/integrated" +use "std/sys" // Operating system specific path separator. const Separator = '\\' @@ -158,7 +158,7 @@ fn abs(mut path: str): (str, ok: bool) { } fn join(elem: ...str): str { - mut s := strings::StrBuilder.New(1 << 4) + mut s := strings::Builder.New(1 << 4) mut lastChar := byte(0) for (_, mut e) in elem { match { diff --git a/std/fs/stat.jule b/std/fs/stat.jule index 2c2c64e38..aa9617183 100644 --- a/std/fs/stat.jule +++ b/std/fs/stat.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" enum statusMode { Na: 0 << 0, diff --git a/std/fs/stat_unix.jule b/std/fs/stat_unix.jule index 315c82774..899650b53 100644 --- a/std/fs/stat_unix.jule +++ b/std/fs/stat_unix.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use sys for std::sys +use integ "std/jule/integrated" +use "std/sys" impl Status { // Returns a Status describing the path. @@ -11,7 +11,7 @@ impl Status { // Possible errors: Denied IO Loop LongPath NotExist NotDir Overflow static fn Of(path: str)!: &Status { if path == "" { - error(FsError.NotExist) + error(Error.NotExist) } mut handle := sys::SysStat{} s := integ::StrToBytes(path) diff --git a/std/fs/stat_windows.jule b/std/fs/stat_windows.jule index 8f5b0b27c..1f6f42b76 100644 --- a/std/fs/stat_windows.jule +++ b/std/fs/stat_windows.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use sys for std::sys +use integ "std/jule/integrated" +use "std/sys" impl Status { // Returns a Status describing the path. @@ -11,10 +11,10 @@ impl Status { // Possible errors: Denied IO Loop LongPath NotExist NotDir Overflow static fn Of(path: str)!: &Status { if path == "" { - error(FsError.NotExist) + error(Error.NotExist) } utf16Path := integ::UTF16FromStr(path) - mut handle := std::sys::SysStat{} + mut handle := sys::SysStat{} code := unsafe { sys::Wstat(&utf16Path[0], &handle) } if code == -1 { error(getLastFsError()) diff --git a/std/hash/adler32/adler32.jule b/std/hash/adler32/adler32.jule index d7f36b96c..608592dfb 100644 --- a/std/hash/adler32/adler32.jule +++ b/std/hash/adler32/adler32.jule @@ -45,7 +45,25 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use hash for std::hash +use "std/hash" + +// The size of an Adler-32 checksum in bytes. +const Size = 4 + +// Returns a new hash::Hash32 computing the Adler-32 checksum. Its +// Sum method will lay the value out in big-endian byte order. +fn New(): hash::Hash32 { + mut d := new(adler32) + d.Reset() + ret d +} + +// Returns the Adler-32 checksum of data. +fn Checksum(data: []byte): u32 { + mut d := adler32{d: 1} + d.update(data) + ret u32(d.d) +} // Largest prime that is less than 65536. const mod = 65521 @@ -62,31 +80,13 @@ const marshaledSize = len(magic) + 4 // The low 16 bits are s1, the high 16 bits are s2. type digest: u32 -struct Adler32 { +struct adler32 { d: digest } -impl hash::Hash32 for Adler32 {} - -impl Adler32 { - // The size of an Adler-32 checksum in bytes. - const Size = 4 - - // Returns a new hash::Hash32 computing the Adler-32 checksum. Its - // Sum method will lay the value out in big-endian byte order. - static fn New(): hash::Hash32 { - mut d := new(Adler32) - d.Reset() - ret d - } - - // Returns the Adler-32 checksum of data. - static fn Checksum(data: []byte): u32 { - mut d := Adler32{d: 1} - d.update(data) - ret u32(d.d) - } +impl hash::Hash32 for adler32 {} +impl adler32 { // Add p to the running checksum. fn update(mut self, p: []byte) { mut s1 := u32(self.d & 0xffff) @@ -125,7 +125,7 @@ impl Adler32 { self.d = 1 } - fn Size(self): int { ret Adler32.Size } + fn Size(self): int { ret Size } fn BlockSize(self): int { ret 4 } diff --git a/std/hash/adler32/adler32_test.jule b/std/hash/adler32/adler32_test.jule index cbfcfe27c..618358bef 100644 --- a/std/hash/adler32/adler32_test.jule +++ b/std/hash/adler32/adler32_test.jule @@ -4,9 +4,9 @@ #build test -use std::unsafe -use testing for std::testing -use strings for std::strings +use "std/strings" +use "std/testing" +use "std/unsafe" struct case { out: u32 @@ -63,7 +63,7 @@ static cases: []case = [ #test fn testChecksum(t: &testing::T) { for _, case in cases { - s := Adler32.Checksum(unsafe::StrBytes(case.input)) + s := Checksum(unsafe::StrBytes(case.input)) if s != case.out { t.Errorf("expected {} for {}, found {}", case.out, case.input, s) } diff --git a/std/hash/fnv/fnv.jule b/std/hash/fnv/fnv.jule index 13684b9bc..76ed461d3 100644 --- a/std/hash/fnv/fnv.jule +++ b/std/hash/fnv/fnv.jule @@ -44,9 +44,9 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use bits for std::math::bits -use hash for std::hash -use byteorder for std::internal::byteorder +use "std/hash" +use "std/internal/byteorder" +use "std/math/bits" const offset32 = 2166136261 const offset64 = 14695981039346656037 @@ -209,49 +209,44 @@ impl hash::Hash for fnv128a { } } -// Static method wrapper for FNV-1 algorithms. -struct Fnv {} - -impl Fnv { - // Returns a new 32-bit FNV-1 [hash::Hash]. - // Its Sum method will lay the value out in big-endian byte order. - static fn New32(): hash::Hash32 { - ret fnv32{s: offset32} - } +// Returns a new 32-bit FNV-1 [hash::Hash]. +// Its Sum method will lay the value out in big-endian byte order. +fn New32(): hash::Hash32 { + ret fnv32{s: offset32} +} - // Returns a new 64-bit FNV-1 [hash::Hash]. - // Its Sum method will lay the value out in big-endian byte order. - static fn New64(): hash::Hash64 { - ret fnv64{s: offset64} - } +// Returns a new 64-bit FNV-1 [hash::Hash]. +// Its Sum method will lay the value out in big-endian byte order. +fn New64(): hash::Hash64 { + ret fnv64{s: offset64} +} - // Returns a new 128-bit FNV-1 [hash::Hash]. - // Its Sum method will lay the value out in big-endian byte order. - static fn New128(): hash::Hash { - mut h := fnv128{} - h.s[0] = offset128Higher - h.s[1] = offset128Lower - ret h - } +// Returns a new 128-bit FNV-1 [hash::Hash]. +// Its Sum method will lay the value out in big-endian byte order. +fn New128(): hash::Hash { + mut h := fnv128{} + h.s[0] = offset128Higher + h.s[1] = offset128Lower + ret h +} - // Returns a new 32-bit FNV-1a [hash::Hash]. - // Its Sum method will lay the value out in big-endian byte order. - static fn New32a(): hash::Hash32 { - ret fnv32a{s: offset32} - } +// Returns a new 32-bit FNV-1a [hash::Hash]. +// Its Sum method will lay the value out in big-endian byte order. +fn New32a(): hash::Hash32 { + ret fnv32a{s: offset32} +} - // Returns a new 64-bit FNV-1a [hash::Hash]. - // Its Sum method will lay the value out in big-endian byte order. - static fn New64a(): hash::Hash64 { - ret fnv64a{s: offset64} - } +// Returns a new 64-bit FNV-1a [hash::Hash]. +// Its Sum method will lay the value out in big-endian byte order. +fn New64a(): hash::Hash64 { + ret fnv64a{s: offset64} +} - // Returns a new 128-bit FNV-1a [hash::Hash]. - // Its Sum method will lay the value out in big-endian byte order. - static fn New128a(): hash::Hash { - mut h := fnv128a{} - h.s[0] = offset128Higher - h.s[1] = offset128Lower - ret h - } +// Returns a new 128-bit FNV-1a [hash::Hash]. +// Its Sum method will lay the value out in big-endian byte order. +fn New128a(): hash::Hash { + mut h := fnv128a{} + h.s[0] = offset128Higher + h.s[1] = offset128Lower + ret h } \ No newline at end of file diff --git a/std/hash/fnv/fnv_test.jule b/std/hash/fnv/fnv_test.jule index 11b51f358..efae827a8 100644 --- a/std/hash/fnv/fnv_test.jule +++ b/std/hash/fnv/fnv_test.jule @@ -4,10 +4,10 @@ #build test -use std::unsafe -use testing for std::testing -use hash for std::hash -use fastbytes for std::internal::fastbytes +use "std/hash" +use "std/internal/fastbytes" +use "std/testing" +use "std/unsafe" struct case { out: []byte @@ -76,30 +76,30 @@ fn testCase(t: &testing::T, mut h: hash::Hash, &cases: []case) { #test fn testCase32(t: &testing::T) { - testCase(t, Fnv.New32(), case32) + testCase(t, New32(), case32) } #test fn testCase32a(t: &testing::T) { - testCase(t, Fnv.New32a(), case32a) + testCase(t, New32a(), case32a) } #test fn testCase64(t: &testing::T) { - testCase(t, Fnv.New64(), case64) + testCase(t, New64(), case64) } #test fn testCase64a(t: &testing::T) { - testCase(t, Fnv.New64a(), case64a) + testCase(t, New64a(), case64a) } #test fn testCase128(t: &testing::T) { - testCase(t, Fnv.New128(), case128) + testCase(t, New128(), case128) } #test fn testCase128a(t: &testing::T) { - testCase(t, Fnv.New128a(), case128a) + testCase(t, New128a(), case128a) } \ No newline at end of file diff --git a/std/hash/hash.jule b/std/hash/hash.jule index 6be09ef78..8c8345ed4 100644 --- a/std/hash/hash.jule +++ b/std/hash/hash.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use io for std::io +use "std/io" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/0700bcfa2e997118f82c6c441406e4ff0a573571/src/hash/hash.go and came with this notice. diff --git a/std/internal/conv/atoi_test.jule b/std/internal/conv/atoi_test.jule index a886471a9..3d7508f28 100644 --- a/std/internal/conv/atoi_test.jule +++ b/std/internal/conv/atoi_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" struct atoiCase { s: str diff --git a/std/internal/conv/itoa.jule b/std/internal/conv/itoa.jule index 783eca240..7b0f03794 100755 --- a/std/internal/conv/itoa.jule +++ b/std/internal/conv/itoa.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe +use "std/unsafe" // Returns x in decimal string format. fn Itoa(x: int): str { diff --git a/std/internal/conv/itoa_test.jule b/std/internal/conv/itoa_test.jule index 04e9a2130..b9477ba53 100644 --- a/std/internal/conv/itoa_test.jule +++ b/std/internal/conv/itoa_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" struct itoaCase { i: int diff --git a/std/internal/fastbytes/fastbytes_test.jule b/std/internal/fastbytes/fastbytes_test.jule index 963022d3c..0a4c3c2b0 100644 --- a/std/internal/fastbytes/fastbytes_test.jule +++ b/std/internal/fastbytes/fastbytes_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" struct equalCase { s1: []byte diff --git a/std/internal/fmt/format.jule b/std/internal/fmt/format.jule index 38e1b1252..1cc28da7c 100644 --- a/std/internal/fmt/format.jule +++ b/std/internal/fmt/format.jule @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use conv for std::conv -use integ for std::jule::integrated -use utf8 for std::unicode::utf8 -use strings for std::internal::strings -use runtime for std::runtime +use "std/conv" +use "std/internal/strings" +use integ "std/jule/integrated" +use "std/runtime" +use "std/unicode/utf8" +use "std/unsafe" fn findFormatPrefix(&bytes: []byte, mut i: int): int { for i < len(bytes) { @@ -45,7 +45,7 @@ fn getFormatRange(mut &i: int, mut &bytes: []byte): []byte { } // Formats arg by default format and appends to buf. -fn FmtByDefault(mut &buf: strings::StrBuilder, &arg: any) { +fn FmtByDefault(mut &buf: strings::Builder, &arg: any) { if arg == nil { buf.WriteStr("") ret @@ -84,7 +84,7 @@ fn FmtByDefault(mut &buf: strings::StrBuilder, &arg: any) { } } -fn applyFmtByDefault(mut &buf: strings::StrBuilder, mut &j: int, args: ...any) { +fn applyFmtByDefault(mut &buf: strings::Builder, mut &j: int, args: ...any) { arg := args[j] j++ FmtByDefault(buf, arg) @@ -92,7 +92,7 @@ fn applyFmtByDefault(mut &buf: strings::StrBuilder, mut &j: int, args: ...any) { // Returns result of formatting. // Parameter j is the position of argument list. -fn applyFmt(mut &fmt: []byte, mut &buf: strings::StrBuilder, mut &j: int, args: ...any) { +fn applyFmt(mut &fmt: []byte, mut &buf: strings::Builder, mut &j: int, args: ...any) { // {} if len(fmt) == 2 { applyFmtByDefault(buf, j, args...) @@ -124,7 +124,7 @@ fn Format(fmt: str, args: ...any): []byte { } mut j := 0 mut last := 0 - mut buf := strings::StrBuilder.New(len(fmt)) + mut buf := strings::Builder.New(len(fmt)) for i != -1; i = findFormatPrefix(fmtBytes, i) { buf.Write(fmtBytes[last:i]) mut format := getFormatRange(i, fmtBytes) diff --git a/std/internal/strings/builder.jule b/std/internal/strings/builder.jule index efbad9158..303be9424 100644 --- a/std/internal/strings/builder.jule +++ b/std/internal/strings/builder.jule @@ -2,21 +2,21 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use utf8 for std::unicode::utf8 +use "std/unicode/utf8" +use "std/unsafe" -// See [std::strings] for documentation. -struct StrBuilder { +// See "std/strings" for documentation. +struct Builder { buf: []byte } -impl StrBuilder { +impl Builder { // Returns new string builder with capacity. - static fn New(cap: int): StrBuilder { + static fn New(cap: int): Builder { if cap < 0 { - panic("std::strings: StrBuilder.New: cap < 0") + panic("strings: Builder.New: cap < 0") } - ret StrBuilder{ + ret Builder{ buf: make([]byte, 0, cap), } } diff --git a/std/io/file.jule b/std/io/file.jule index 35206c0d9..cc71fc32c 100644 --- a/std/io/file.jule +++ b/std/io/file.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fs for std::fs -use strings for std::internal::strings +use "std/fs" +use "std/internal/strings" +use "std/unsafe" // Stream implementation for file handles. // Uses internally mutable buffer. @@ -71,7 +71,7 @@ impl FileStream { fn ReadLine(mut self)!: str { const LINE_DELIMITER = '\n' - mut buf := strings::StrBuilder.New(1 << 10) + mut buf := strings::Builder.New(1 << 10) let mut partBuff: bufferArray mut part := unsafe::Slice(&partBuff[0], len(partBuff), len(partBuff)) for { diff --git a/std/io/io.jule b/std/io/io.jule index e8ce7dcfa..6f2e40e29 100644 --- a/std/io/io.jule +++ b/std/io/io.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use fs for std::fs -use sys for std::sys +use "std/fs" +use "std/sys" // Typically element type used for buffering arrays. type bufferArrayElem: byte diff --git a/std/io/scan.jule b/std/io/scan.jule index 0fa47fd54..991fe7165 100644 --- a/std/io/scan.jule +++ b/std/io/scan.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fs for std::fs +use "std/fs" +use "std/unsafe" // Scanner for files or etc. // Scans bytes line-by-line. diff --git a/std/jule/README.md b/std/jule/README.md index 98809302e..81a3e841c 100644 --- a/std/jule/README.md +++ b/std/jule/README.md @@ -1,4 +1,4 @@ -# `std::jule` +# `std/jule` This package contains tools such as lexer, parser, semantic analyzer for Jule.\ It is also used by the official reference compiler JuleC and is developed in parallel. @@ -6,7 +6,7 @@ It is also used by the official reference compiler JuleC and is developed in par ## Packages - [`ast`](./ast): AST things. -- [`lex`](./lex): Lexical analyzer. +- [`token`](./token): Lexical analyzer. - [`importer`](./importer): Default Jule importer. - [`parser`](./parser): Parser. - [`sema`](./sema): Semantic analyzer and CAST (Compilation Abstract Syntax Tree) components. @@ -55,7 +55,7 @@ For example: \ These packages are specially processed and treated differently than standard use declarations. These treatments only apply to supported packages. To see relevant treatments, see implicit imports section of the reference.\ \ -Typical uses are things like capturing or tracing private behavior. For example, the reference Jule compiler may embed the `std::runtime` package for some special calls. The semantic analyzer makes the necessary private calls for this embedded package when necessary. For example, appends instance to array compare generic method for array comparions. +Typical uses are things like capturing or tracing private behavior. For example, the reference Jule compiler may embed the `std/runtime` package for some special calls. The semantic analyzer makes the necessary private calls for this embedded package when necessary. For example, appends instance to array compare generic method for array comparions. - **(9.1)** The `Token` field is used to distinguish specific packages. If the `Token` field of the AST element is set to `nil`, the package built-in use declaration is considered. Accordingly, AST must always set the `Token` field for each use declaration which is not implicitly imported. - **(9.2)** Semantic analyzer will ignore implicit use declaration for duplication analysis. So, built-in implicit imported packages may be duplicated if placed source file contains separate use declaration for the same package. - **(9.3)** These packages should be placed as first use declarations of the main package's first file. @@ -69,7 +69,7 @@ Typical uses are things like capturing or tracing private behavior. For example, Implicit imports are as described in developer reference (9). This section addresses which package is supported and what special behaviors it has. -#### `std::runtime` +#### `std/runtime` This package is a basic package developed for Jule programs and focuses on runtime functionalities. diff --git a/std/jule/ast/ast.jule b/std/jule/ast/ast.jule index 128bab932..1aa9ce76c 100644 --- a/std/jule/ast/ast.jule +++ b/std/jule/ast/ast.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex +use "std/jule/token" // Abstract syntax tree. struct AST { - File: &lex::File + File: &token::Fileset TopDirectives: []&Directive UseDecls: []&UseDecl Nodes: []Node diff --git a/std/jule/ast/node.jule b/std/jule/ast/node.jule index d7451fdff..ef43ec982 100644 --- a/std/jule/ast/node.jule +++ b/std/jule/ast/node.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex +use "std/jule/token" // Type of AST Node's data. enum NodeData: type { @@ -18,14 +18,14 @@ enum NodeData: type { // AST Node. struct Node { - Token: &lex::Token + Token: &token::Token Data: NodeData } // Directive. struct Directive { - Tag: &lex::Token - Args: []&lex::Token + Tag: &token::Token + Args: []&token::Token } // Kind type of type declarations. @@ -53,13 +53,13 @@ enum TypeDeclKind: type { // For function types: // - Function types represented by &FnDecl. struct TypeDecl { - Token: &lex::Token + Token: &token::Token Kind: TypeDeclKind } // Identifier type. struct IdentTypeDecl { - Token: &lex::Token + Token: &token::Token Ident: str Binded: bool Generics: []&TypeDecl @@ -72,8 +72,8 @@ struct SubIdentTypeDecl { // Namespace chain type. struct NamespaceTypeDecl { - Idents: []&lex::Token // Namespace chain with identifier tokens. - Kind: &TypeDecl // Type of identifier. + Namespace: &token::Token // Namespace token. + Kind: &TypeDecl // Type of identifier. } // Smart pointer type. @@ -127,7 +127,7 @@ struct MapTypeDecl { // Kind and Idents is nil for void type. struct RetTypeDecl { Kind: &TypeDecl - Idents: []&lex::Token + Idents: []&token::Token } // Type of Expr's data. @@ -139,7 +139,7 @@ enum ExprData: type { &IdentExpr, &UnaryExpr, &SubIdentExpr, - &NsSelectionExpr, + &NamespaceExpr, &VariadicExpr, &CastExpr, &FnCallExpr, @@ -157,8 +157,8 @@ enum ExprData: type { // Expression. struct Expr { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Kind: ExprData } @@ -169,7 +169,7 @@ struct RangeExpr { // Use expression. struct UseExpr { - Token: &lex::Token + Token: &token::Token Expr: &Expr } @@ -180,19 +180,19 @@ struct TupleExpr { // Literal expression. struct LitExpr { - Token: &lex::Token + Token: &token::Token Value: str } // Unsafe expression. struct UnsafeExpr { - Token: &lex::Token // Token of unsafe keyword. + Token: &token::Token // Token of unsafe keyword. Expr: &Expr } // Identifier expression. struct IdentExpr { - Token: &lex::Token // Token of identifier. + Token: &token::Token // Token of identifier. Ident: str Binded: bool } @@ -200,19 +200,19 @@ struct IdentExpr { impl IdentExpr { // Reports whether identifier is self keyword. fn IsSelf(self): bool { - ret self.Ident == lex::TokenKind.Self + ret self.Ident == token::Kind.Self } } // Unary expression. struct UnaryExpr { - Op: &lex::Token + Op: &token::Token Expr: &Expr } // Variadiced expression. struct VariadicExpr { - Token: &lex::Token + Token: &token::Token Expr: &Expr } @@ -223,27 +223,27 @@ struct CastExpr { } // Namespace identifier selection expression. -struct NsSelectionExpr { - Ns: []&lex::Token // Tokens of selected namespace identifier chain. - Ident: &lex::Token // Token of selected identifier. +struct NamespaceExpr { + Namespace: &token::Token // Tokens of namespace identifier. + Ident: &token::Token // Token of selected identifier. } // Object sub identifier selection expression. struct SubIdentExpr { - Expr: &Expr // Selected object. - Ident: &lex::Token // TOken of selected identifier. + Expr: &Expr // Selected object. + Ident: &token::Token // TOken of selected identifier. } // Binary operation. struct BinaryExpr { Left: &Expr Right: &Expr - Op: &lex::Token + Op: &token::Token } // Function call expression kind. struct FnCallExpr { - Token: &lex::Token + Token: &token::Token Expr: &Expr Args: []&Expr Exception: &ScopeTree // Exception handling scope. @@ -266,7 +266,7 @@ impl FnCallExpr { // Field-Expression pair. struct FieldExprPair { - Field: &lex::Token // Field identifier token. + Field: &token::Token // Field identifier token. Expr: &Expr } @@ -279,15 +279,15 @@ impl FieldExprPair { // Struct literal instiating expression. struct StructLit { - End: &lex::Token + End: &token::Token Kind: &TypeDecl Exprs: []&Expr // Possible types: &FieldExprPair, and other expressions. } // Anonymous brace instiating expression. struct BraceLit { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Exprs: []&Expr } @@ -302,14 +302,14 @@ impl BraceLit { struct KeyValPair { Key: &Expr Val: &Expr - Colon: &lex::Token + Colon: &token::Token } // Slice initiating expression. // Also represents array initiating expression. struct SliceExpr { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Exprs: []&Expr } @@ -322,16 +322,16 @@ impl SliceExpr { // Indexing expression. struct IndexingExpr { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Expr: &Expr // Value expression to indexing. Index: &Expr // Index value expression. } // Slicing expression. struct SlicingExpr { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Expr: &Expr // Value expression to slicing. Start: &Expr // Start index value expression. To: &Expr // To index value expression. @@ -344,31 +344,31 @@ struct Constraint { // Generic type declaration. struct GenericDecl { - Token: &lex::Token + Token: &token::Token Ident: str Constraint: &Constraint } // Label statement. struct LabelSt { - Token: &lex::Token + Token: &token::Token Ident: str } // Goto statement. struct GotoSt { - Token: &lex::Token - Label: &lex::Token + Token: &token::Token + Label: &token::Token } // Fall statement. struct FallSt { - Token: &lex::Token + Token: &token::Token } // Left expression of assign statement. struct AssignLeft { - Token: &lex::Token + Token: &token::Token Mutable: bool Reference: bool Ident: str @@ -378,7 +378,7 @@ struct AssignLeft { // Assign statement. struct AssignSt { Declarative: bool - Setter: &lex::Token + Setter: &token::Token Left: []&AssignLeft Right: &Expr } @@ -404,7 +404,7 @@ enum StmtData: type { // Statement. struct Stmt { - Token: &lex::Token + Token: &token::Token Data: StmtData } @@ -414,12 +414,12 @@ struct ScopeTree { Unsafety: bool Deferred: bool Stmts: []Stmt - End: &lex::Token + End: &token::Token } // Parameter. struct ParamDecl { - Token: &lex::Token + Token: &token::Token Mutable: bool Variadic: bool Reference: bool @@ -442,7 +442,7 @@ impl ParamDecl { // Function declaration. // Also represents anonymous function expression. struct FnDecl { - Token: &lex::Token + Token: &token::Token Global: bool Unsafety: bool Public: bool @@ -460,15 +460,15 @@ struct FnDecl { impl FnDecl { // Reports whether function is anonymous. fn IsAnon(self): bool { - ret self.Ident == lex::Ident.Anon + ret self.Ident == token::Ident.Anon } } // Variable declaration. struct VarDecl { Scope: &ScopeTree // nil for global scopes - Token: &lex::Token - Setter: &lex::Token + Token: &token::Token + Setter: &token::Token Ident: str Binded: bool Public: bool @@ -483,7 +483,7 @@ struct VarDecl { // Return statement. struct RetSt { - Token: &lex::Token + Token: &token::Token Expr: &Expr } @@ -496,7 +496,7 @@ enum IterKind: type { // Iteration. struct Iter { Comptime: bool - Token: &lex::Token + Token: &token::Token Kind: IterKind Scope: &ScopeTree } @@ -510,7 +510,7 @@ impl Iter { struct WhileKind { Expr: &Expr Next: StmtData // Nil if kind is while-next iteration. - NextToken: &lex::Token + NextToken: &token::Token } impl WhileKind { @@ -522,7 +522,7 @@ impl WhileKind { // Range iteration kind. struct RangeKind { - InToken: &lex::Token // Token of "in" keyword + InToken: &token::Token // Token of "in" keyword Expr: &Expr KeyA: &VarDecl // first key of range KeyB: &VarDecl // second key of range @@ -530,26 +530,26 @@ struct RangeKind { // Break statement. struct BreakSt { - Token: &lex::Token - Label: &lex::Token + Token: &token::Token + Label: &token::Token } // Continue statement. struct ContSt { - Token: &lex::Token - Label: &lex::Token + Token: &token::Token + Label: &token::Token } // If condition. struct If { - Token: &lex::Token + Token: &token::Token Expr: &Expr Scope: &ScopeTree } // Else condition. struct Else { - Token: &lex::Token + Token: &token::Token Scope: &ScopeTree } @@ -565,14 +565,14 @@ struct TypeAliasDecl { Scope: &ScopeTree Public: bool Binded: bool - Token: &lex::Token + Token: &token::Token Ident: str Kind: &TypeDecl } // Case of match-case. struct Case { - Token: &lex::Token + Token: &token::Token Scope: &ScopeTree // Holds expression. @@ -583,8 +583,8 @@ struct Case { // Match-Case. struct MatchCase { Comptime: bool - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token TypeMatch: bool Expr: &Expr Cases: []&Case @@ -593,18 +593,15 @@ struct MatchCase { // Use declaration statement. struct UseDecl { - Token: &lex::Token - LinkPath: str // Use declaration path string. - Alias: str - Full: bool // Full implicit import. - Selected: []&lex::Token - Binded: bool // Bind use declaration. - Std: bool // Standard package use declaration. + Token: &token::Token + Path: &token::Token // Use declaration path token. + Alias: &token::Token // Custom alias. Nil if not given. + Binded: bool // Bind use declaration. } // Enum item. struct EnumItemDecl { - Token: &lex::Token + Token: &token::Token Ident: str Expr: &Expr // Nil for auto expression. } @@ -618,12 +615,12 @@ impl EnumItemDecl { // Enum declaration. struct EnumDecl { - Token: &lex::Token + Token: &token::Token Public: bool Ident: str Kind: &TypeDecl Items: []&EnumItemDecl - End: &lex::Token + End: &token::Token } impl EnumDecl { @@ -635,23 +632,23 @@ impl EnumDecl { // TypeEnum item. struct TypeEnumItemDecl { - Token: &lex::Token + Token: &token::Token Ident: str Kind: &TypeDecl } // TypeEnum declaration. struct TypeEnumDecl { - Token: &lex::Token + Token: &token::Token Public: bool Ident: str Items: []&TypeEnumItemDecl - End: &lex::Token + End: &token::Token } // Field declaration. struct FieldDecl { - Token: &lex::Token + Token: &token::Token Public: bool Mutable: bool // Interior mutability. Ident: str @@ -661,8 +658,8 @@ struct FieldDecl { // Structure declaration. struct StructDecl { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Ident: str Fields: []&FieldDecl Public: bool @@ -673,8 +670,8 @@ struct StructDecl { // Trait declaration. struct TraitDecl { - Token: &lex::Token - End: &lex::Token + Token: &token::Token + End: &token::Token Ident: str Public: bool Inherits: []&TypeDecl @@ -683,7 +680,7 @@ struct TraitDecl { // Implementation. struct Impl { - End: &lex::Token + End: &token::Token // This token available for these cases: // - Implementation trait to structure, represents trait's type. diff --git a/std/jule/build/env.jule b/std/jule/build/env.jule index 37df4e620..99496f32c 100644 --- a/std/jule/build/env.jule +++ b/std/jule/build/env.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path -use env for std::env -use process for std::process +use "std/env" +use "std/fs/path" +use "std/process" // Environment Variables. // Initialized by initializer function. @@ -24,13 +24,13 @@ static mut Arch = env::Arch fn init() { mut path := process::Executable() if path == "" { - panic("std::jule::build: executable file cannot found") + panic("build: executable file cannot found") } // Break immutability to assign paths. unsafe { *(&PathWd) = env::WorkingDir() else { - panic("std::jule::build: working directory path cannot found") + panic("build: working directory path cannot found") ret // To avoid assignment error. } *(&PathExec) = path::Dir(path) diff --git a/std/jule/build/jule.jule b/std/jule/build/jule.jule index 2068da7dd..7a7546c1e 100644 --- a/std/jule/build/jule.jule +++ b/std/jule/build/jule.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path +use "std/fs/path" // Extension (includes dot) of Jule source code files. const Ext = `.jule` @@ -22,5 +22,8 @@ const InitFn = "init" // Filename of module file. const ModuleFile = "jule.mod" +// Separator of import paths. +const ImportPathSep = "/" + // Reports whether file path is Jule source code. fn IsJule(path: str): bool { ret path::Ext(path) == Ext } \ No newline at end of file diff --git a/std/jule/build/log.jule b/std/jule/build/log.jule index baa3feee6..f2ec03dfa 100644 --- a/std/jule/build/log.jule +++ b/std/jule/build/log.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use strings for std::internal::strings +use "std/internal/strings" // Compiler log messages with formatting. enum LogMsg: str { @@ -242,13 +242,14 @@ enum LogMsg: str { AnonFn: `anonymous functions are not allowed in this scope`, CopyWithMutableData: `struct @ cannot copied due to field which is stores mutable data`, CalledOutOfScope: `you can call @ function in the scopes only`, - BlankIdentInUseDecl: `use declaration paths cannot contain blank identifier`, ComptimeExprForRuntimeIteration: `comptime expressions cannot be iterated at runtime`, InvalidTypeForComptimeIter: `type @ is not supports comptime iterations`, InvalidComptimeIter: `comptime iterations can only be range iteration`, InvalidComptimeTypeMatchExpr: `comptime type-match expressions can take only type declarations`, WrongRetForward: "function return forwaring is wrong\n want (@)\n have (@)", ExportedUsedAsAnonymous: `define @ is exported for backend so you cannot use as anonymous function`, + InvalidImportPath: `invalid import path: @`, + AutoAliasFail: `import path is not suitable for auto-aliasing: @`, // Suggestions. ExpectedIdentifier: `write an identifier because identifier expected`, @@ -299,6 +300,7 @@ enum LogMsg: str { UseUnsafeJuleToCallCoSelf: `use "&self" receiver parameter instead, or Unsafe Jule with unsafe {} scope to make concurrent call`, DefineZeroDefaultToUseAmper: `define default enum field (the first one is default) with zero value to use & operator`, InvalidExprForConstMatch: `comptime-matching requires constant expression`, + GiveAnAliasManually: `give an alias manually to import path, like: use @`, } // Log kinds. @@ -346,7 +348,7 @@ fn findNextFmt(fmt: str): int { } fn applyFmt(mut fmt: str, args: ...any): str { - mut s := strings::StrBuilder.New(1 << 5) + mut s := strings::Builder.New(1 << 5) for _, arg in args { i := findNextFmt(fmt) if i == -1 { diff --git a/std/jule/build/platform.jule b/std/jule/build/platform.jule index a8c479f26..dfa51030d 100644 --- a/std/jule/build/platform.jule +++ b/std/jule/build/platform.jule @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -// List of all possible std::runtime::OS values: +// List of all possible env::Os values: enum runtimeOs: str { Windows: "windows", Darwin: "darwin", Linux: "linux", } -// List of all possible std::runtime::ARCH values: +// List of all possible env::Arch values: enum runtimeArch: str { I386: "i386", Amd64: "amd64", diff --git a/std/jule/constant/lit/bytes.jule b/std/jule/constant/lit/bytes.jule index 66a1e759d..a47081ab3 100644 --- a/std/jule/constant/lit/bytes.jule +++ b/std/jule/constant/lit/bytes.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use conv for std::conv -use utf8 for std::unicode::utf8 +use "std/conv" +use "std/unicode/utf8" +use "std/unsafe" // Reports whether rune is byte actually. // In other words, whether rune is ACII. diff --git a/std/jule/importer/annotation.jule b/std/jule/importer/annotation.jule index f4f95e4c2..ce09a36f6 100644 --- a/std/jule/importer/annotation.jule +++ b/std/jule/importer/annotation.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path -use build for std::jule::build -use strings for std::strings +use "std/fs/path" +use "std/jule/build" +use "std/strings" fn checkOs(arg: str): (ok: bool, exist: bool) { ok = false diff --git a/std/jule/importer/directive_eval.jule b/std/jule/importer/directive_eval.jule index 85f7bd36a..a44249582 100644 --- a/std/jule/importer/directive_eval.jule +++ b/std/jule/importer/directive_eval.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" // Eval directive expression. // Directive expressions are logial expressions and uses varaibles. @@ -18,7 +18,7 @@ struct directiveEval { } impl directiveEval { - fn pushErr(mut self, t: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, t: &token::Token, fmt: build::LogMsg, args: ...any) { self.logs = append(self.logs, build::Log{ Kind: build::LogKind.Error, Row: t.Row, @@ -30,18 +30,18 @@ impl directiveEval { // Split operans by binary operators. // Skips range of parentheses. - fn splitOperans(mut self, op: lex::TokenId, mut &tokens: []&lex::Token): [][]&lex::Token { - mut parts := make([][]&lex::Token, 0, 10) + fn splitOperans(mut self, op: token::Id, mut &tokens: []&token::Token): [][]&token::Token { + mut parts := make([][]&token::Token, 0, 10) mut i := 0 mut rangeN := 0 mut last := 0 for i < len(tokens)-1; i++ { b := tokens[i] match b.Id { - | lex::TokenId.LParent: + | token::Id.LParent: rangeN++ continue - | lex::TokenId.RParent: + | token::Id.RParent: rangeN-- } if rangeN > 0 || b.Id != op { @@ -75,8 +75,8 @@ impl directiveEval { // Eval directive expression part. // Accepts unary operators. - fn evalDirectivePart(mut self, mut part: []&lex::Token): bool { - logicalNot := part[0].Id == lex::TokenId.Excl + fn evalDirectivePart(mut self, mut part: []&token::Token): bool { + logicalNot := part[0].Id == token::Id.Excl if logicalNot { part = part[1:] } @@ -101,25 +101,25 @@ impl directiveEval { mut result := false - mut logicalOrParts := self.splitOperans(lex::TokenId.DblVline, self.d.Args) + mut logicalOrParts := self.splitOperans(token::Id.DblVline, self.d.Args) if logicalOrParts == nil { ret false } for (_, mut part) in logicalOrParts { mut and := true - mut logicalAndParts := self.splitOperans(lex::TokenId.DblAmper, part) + mut logicalAndParts := self.splitOperans(token::Id.DblAmper, part) if logicalAndParts == nil { ret false } for (_, mut andPart) in logicalAndParts { first := andPart[0] - if first.Id == lex::TokenId.LParent { + if first.Id == token::Id.LParent { end := andPart[len(andPart)-1] // Missing close. - if end.Id != lex::TokenId.RParent { + if end.Id != token::Id.RParent { self.pushErr(first, build::LogMsg.WaitCloseParent) ret false } diff --git a/std/jule/importer/importer.jule b/std/jule/importer/importer.jule index e80f3cec2..581d32c59 100644 --- a/std/jule/importer/importer.jule +++ b/std/jule/importer/importer.jule @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use fs for std::fs -use path for std::fs::path -use ast for std::jule::ast -use build for std::jule::build -use mod for std::jule::internal::mod -use lex for std::jule::lex -use parser for std::jule::parser -use sema for std::jule::sema -use process for std::process -use strings for std::strings +use "std/fs" +use "std/fs/path" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/internal/mod" +use "std/jule/parser" +use "std/jule/sema" +use "std/jule/token" +use "std/process" +use "std/strings" // Read buffer by file path. fn readBuff(path: str): []byte { @@ -33,17 +33,17 @@ fn flatCompilerErr(text: str): build::Log { } // Default importer for the reference Jule compiler. -struct JuleImporter { +struct Importer { mods: []str mod: str pkgs: []&sema::ImportInfo vars: []str } -impl JuleImporter { +impl Importer { // Returns new importer instance by compile information. - static fn New(info: CompileInfo): &JuleImporter { - mut imp := &JuleImporter{ + static fn New(info: CompileInfo): &Importer { + mut imp := &Importer{ mods: [build::PathStdlib], } initVars(imp.vars, info) @@ -58,7 +58,7 @@ impl JuleImporter { } } -impl sema::Importer for JuleImporter { +impl sema::Importer for Importer { fn SetModPath(mut self, path: str) { self.mod = path } @@ -105,9 +105,9 @@ impl sema::Importer for JuleImporter { } _path := path::Join(path, dirent.Name) - mut file := lex::NewFileSet(_path) + mut file := token::Fileset.New(_path) file.Fill(readBuff(file.Path)) - mut errors := lex::Lex(file, lex::LexMode.Standard) + mut errors := token::Lex(file, token::Mode.Standard) if len(errors) > 0 { ret nil, errors } @@ -163,7 +163,7 @@ impl sema::Importer for JuleImporter { } } -impl JuleImporter { +impl Importer { // Reports whether file passes build directives. fn isPassBuildDirectives(mut self, mut &file: &ast::AST): (bool, []build::Log) { for (_, mut td) in file.TopDirectives { diff --git a/std/jule/importer/var.jule b/std/jule/importer/var.jule index ed5f6211a..5d333a411 100644 --- a/std/jule/importer/var.jule +++ b/std/jule/importer/var.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use build for std::jule::build +use "std/jule/build" // Standard back-end compilers. enum Compiler: str { diff --git a/std/jule/integrated/conv.jule b/std/jule/integrated/conv.jule index dcf733dea..d17e8dd6e 100644 --- a/std/jule/integrated/conv.jule +++ b/std/jule/integrated/conv.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use utf16 for std::unicode::utf16 +use "std/unicode/utf16" // Returns the UTF-16 encoding of the UTF-8 string // s, with a terminating NULL added. If s includes NULL @@ -68,7 +68,8 @@ unsafe fn BytePtrToStr(s: *byte): str { } mut n := 0 unsafe { - for s[n] != 0; n++ {} + for s[n] != 0; n++ { + } } if n == 0 { ret "" diff --git a/std/jule/internal/mod/export.jule b/std/jule/internal/mod/export.jule index 3b90c2652..83498a3ef 100644 --- a/std/jule/internal/mod/export.jule +++ b/std/jule/internal/mod/export.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use utf8 for std::unicode::utf8 -use unicode for std::unicode +use "std/unicode" +use "std/unicode/utf8" // Reports whether identifier is public. fn IsPub(ident: str): bool { diff --git a/std/jule/internal/mod/mod.jule b/std/jule/internal/mod/mod.jule index 5f02ad06c..b7bf08976 100644 --- a/std/jule/internal/mod/mod.jule +++ b/std/jule/internal/mod/mod.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fs for std::fs -use path for std::fs::path -use build for std::jule::build -use strings for std::strings +use "std/fs" +use "std/fs/path" +use "std/jule/build" +use "std/strings" +use "std/unsafe" // Searches module file in path. // Reports whether module file is exist in given directory. diff --git a/std/jule/parser/assign.jule b/std/jule/parser/assign.jule index f1feb403e..0b1e5a34d 100644 --- a/std/jule/parser/assign.jule +++ b/std/jule/parser/assign.jule @@ -2,31 +2,31 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex +use "std/jule/token" // Assignment information. struct assignInfo { - l: []&lex::Token - r: []&lex::Token - setter: &lex::Token + l: []&token::Token + r: []&token::Token + setter: &token::Token ok: bool } // Checks assignment tokens and whether reports is ok or not. -fn checkAssignTokens(&tokens: []&lex::Token): bool { - if len(tokens) == 0 || !lex::IsAssign(tokens[0].Id) { +fn checkAssignTokens(&tokens: []&token::Token): bool { + if len(tokens) == 0 || !token::IsAssign(tokens[0].Id) { ret false } mut braceN := 0 for _, t in tokens { match t.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: braceN++ - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- } match { @@ -34,7 +34,7 @@ fn checkAssignTokens(&tokens: []&lex::Token): bool { ret false | braceN > 0: continue - | lex::IsAssignOp(t.Id) | t.Id == lex::TokenId.ColonEq: + | token::IsAssignOp(t.Id) | t.Id == token::Id.ColonEq: ret true } } diff --git a/std/jule/parser/expr.jule b/std/jule/parser/expr.jule index 2538375d3..a83e10f97 100644 --- a/std/jule/parser/expr.jule +++ b/std/jule/parser/expr.jule @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" struct exprBuilder { p: &parser } impl exprBuilder { - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.p.pushErr(token, fmt, args...) } @@ -20,7 +20,7 @@ impl exprBuilder { self.p.pushSuggestion(fmt, args...) } - fn buildTuple(mut self, mut &parts: [][]&lex::Token): &ast::TupleExpr { + fn buildTuple(mut self, mut &parts: [][]&token::Token): &ast::TupleExpr { mut tuple := &ast::TupleExpr{ Expr: make([]&ast::Expr, 0, len(parts)), } @@ -30,44 +30,44 @@ impl exprBuilder { ret tuple } - fn buildLit(self, mut token: &lex::Token): &ast::LitExpr { + fn buildLit(self, mut token: &token::Token): &ast::LitExpr { ret &ast::LitExpr{ Token: token, Value: token.Kind, } } - fn buildPrimitiveType(self, mut &token: &lex::Token): &ast::TypeDecl { + fn buildPrimitiveType(self, mut &token: &token::Token): &ast::TypeDecl { ret buildPrimType(token) } - fn buildSingle(mut self, mut token: &lex::Token): ast::ExprData { + fn buildSingle(mut self, mut token: &token::Token): ast::ExprData { match token.Id { - | lex::TokenId.Lit: + | token::Id.Lit: ret self.buildLit(token) - | lex::TokenId.TripleDot: + | token::Id.TripleDot: ret &ast::VariadicExpr{ Token: token, } - | lex::TokenId.Ident - | lex::TokenId.Self - | lex::TokenId.Error: + | token::Id.Ident + | token::Id.Self + | token::Id.Error: ret buildIdentExpr(token) } self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil } - fn buildBindIdent(mut self, mut &tokens: []&lex::Token): &ast::IdentExpr { - if tokens[0].Id != lex::TokenId.Cpp { + fn buildBindIdent(mut self, mut &tokens: []&token::Token): &ast::IdentExpr { + if tokens[0].Id != token::Id.Cpp { ret nil - } else if tokens[1].Id != lex::TokenId.Dot { + } else if tokens[1].Id != token::Id.Dot { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedDotForBind) ret nil } mut token := tokens[2] - if token.Id != lex::TokenId.Ident { + if token.Id != token::Id.Ident { self.pushErr(tokens[2], build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret nil @@ -77,12 +77,12 @@ impl exprBuilder { ret expr } - fn buildUnary(mut self, mut tokens: []&lex::Token): &ast::UnaryExpr { + fn buildUnary(mut self, mut tokens: []&token::Token): &ast::UnaryExpr { mut op := tokens[0] if len(tokens) == 1 { self.pushErr(op, build::LogMsg.MissingExprForUnary) ret nil - } else if !lex::IsUnaryOp(op.Id) { + } else if !token::IsUnaryOp(op.Id) { self.pushErr(op, build::LogMsg.InvalidOpForUnary, op.Kind) ret nil } @@ -98,7 +98,7 @@ impl exprBuilder { } } - fn buildObjSubIdent(mut self, mut tokens: []&lex::Token): &ast::SubIdentExpr { + fn buildObjSubIdent(mut self, mut tokens: []&token::Token): &ast::SubIdentExpr { mut i := len(tokens) - 1 mut identToken := tokens[i] i-- // Set offset to delimiter token. @@ -113,32 +113,41 @@ impl exprBuilder { } } - fn buildNsSubIdent(mut self, mut &tokens: []&lex::Token): &ast::NsSelectionExpr { - mut ns := new(ast::NsSelectionExpr) - if len(tokens) == 3 && tokens[0].Id == lex::TokenId.Unsafe { - // Check unsafe scope selection. - ns.Ns = tokens[:1] - ns.Ident = tokens[2] - } else { - for (i, mut token) in tokens { - if i%2 == 0 { - if token.Id != lex::TokenId.Ident { - self.pushErr(token, build::LogMsg.InvalidSyntax) - self.pushSuggestion(build::LogMsg.ExpectedIdentifier) - } - ns.Ns = append(ns.Ns, token) - } else if token.Id != lex::TokenId.DblColon { - self.pushErr(token, build::LogMsg.InvalidSyntax) - self.pushSuggestion(build::LogMsg.ExpectedDblColon) - } - } - ns.Ident = ns.Ns[len(ns.Ns)-1] - ns.Ns = ns.Ns[:len(ns.Ns)-1] + fn buildNamespace(mut self, mut &tokens: []&token::Token): &ast::NamespaceExpr { + mut ns := new(ast::NamespaceExpr) + if len(tokens) > 3 { + self.pushErr(tokens[3], build::LogMsg.InvalidSyntax) + } + ns.Namespace = tokens[0] + if ns.Namespace.Id != token::Id.Ident && ns.Namespace.Id != token::Id.Unsafe { + self.pushErr(ns.Namespace, build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedIdentifier) + } + if len(tokens) < 2 { + self.pushErr(ns.Namespace, build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedDblColon) + ret nil + } + if tokens[1].Id != token::Id.DblColon { + self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedDblColon) + ret nil + } + if len(tokens) < 3 { + self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedIdentifier) + ret nil + } + ns.Ident = tokens[2] + if ns.Ident.Id != token::Id.Ident { + self.pushErr(ns.Ident, build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedIdentifier) + ret nil } ret ns } - fn buildType(mut self, mut &tokens: []&lex::Token): &ast::TypeDecl { + fn buildType(mut self, mut &tokens: []&token::Token): &ast::TypeDecl { mut i := 0 mut t, ok := unsafe { self.p.buildType(tokens, &i, false) } if !ok { @@ -152,15 +161,15 @@ impl exprBuilder { ret t } - fn buildSubIdent(mut self, mut &tokens: []&lex::Token): ast::ExprData { + fn buildSubIdent(mut self, mut &tokens: []&token::Token): ast::ExprData { i := len(tokens) - 2 // Set offset to delimiter token. token := tokens[i] match token.Id { - | lex::TokenId.Dot: + | token::Id.Dot: ret self.buildObjSubIdent(tokens) - | lex::TokenId.DblColon: - ret self.buildNsSubIdent(tokens) - | lex::TokenId.RBracket: + | token::Id.DblColon: + ret self.buildNamespace(tokens) + | token::Id.RBracket: // Catch slice, array, and map types. ret self.buildType(tokens) } @@ -174,7 +183,7 @@ impl exprBuilder { ret nil } - fn buildVariadic(mut self, mut tokens: []&lex::Token): &ast::VariadicExpr { + fn buildVariadic(mut self, mut tokens: []&token::Token): &ast::VariadicExpr { mut token := tokens[len(tokens)-1] // Variadic operator token. tokens = tokens[:len(tokens)-1] // Remove variadic operator token. ret &ast::VariadicExpr{ @@ -183,7 +192,7 @@ impl exprBuilder { } } - fn buildBetweenParentheses(mut self, mut tokens: []&lex::Token): &ast::RangeExpr { + fn buildBetweenParentheses(mut self, mut tokens: []&token::Token): &ast::RangeExpr { if len(tokens) == 2 { self.pushErr(tokens[0], build::LogMsg.MissingExpr) self.pushSuggestion(build::LogMsg.EmptyParentNotValid) @@ -195,18 +204,18 @@ impl exprBuilder { } } - fn tryBuildCast(mut self, mut &tokens: []&lex::Token): &ast::CastExpr { + fn tryBuildCast(mut self, mut &tokens: []&token::Token): &ast::CastExpr { mut rangeN := 0 for i, token in tokens { match token.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: rangeN++ continue - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: rangeN-- } @@ -225,7 +234,7 @@ impl exprBuilder { } tok := exprTokens[0] - if tok.Id != lex::TokenId.LParent { + if tok.Id != token::Id.LParent { ret nil } @@ -255,7 +264,7 @@ impl exprBuilder { if len(exprTokens) > 2 { // Remove parentheses. mut j := 0 - _ = range(j, lex::TokenId.LParent, lex::TokenId.RParent, exprTokens) + _ = range(j, token::Id.LParent, token::Id.RParent, exprTokens) if j < len(exprTokens) { ret nil } @@ -269,7 +278,7 @@ impl exprBuilder { ret nil } - fn pushArg(mut self, mut &args: []&ast::Expr, mut tokens: []&lex::Token, errToken: &lex::Token) { + fn pushArg(mut self, mut &args: []&ast::Expr, mut tokens: []&token::Token, errToken: &token::Token) { if len(tokens) == 0 { self.pushErr(errToken, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedExpr) @@ -278,7 +287,7 @@ impl exprBuilder { args = append(args, self.buildFromTokens(tokens)) } - fn buildArgs(mut self, mut tokens: []&lex::Token): []&ast::Expr { + fn buildArgs(mut self, mut tokens: []&token::Token): []&ast::Expr { // No argument. if len(tokens) < 2 { ret nil @@ -290,16 +299,16 @@ impl exprBuilder { tokens = tokens[1:len(tokens)-1] // Remove parentheses. for i, token in tokens { match token.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: rangeN++ - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: rangeN-- } - if rangeN > 0 || token.Id != lex::TokenId.Comma { + if rangeN > 0 || token.Id != token::Id.Comma { continue } self.pushArg(args, tokens[last:i], token) @@ -320,13 +329,13 @@ impl exprBuilder { } // Tokens should include brackets. - fn buildCallGenerics(mut self, mut tokens: []&lex::Token): []&ast::TypeDecl { + fn buildCallGenerics(mut self, mut tokens: []&token::Token): []&ast::TypeDecl { if len(tokens) == 0 { ret nil } tokens = tokens[1:len(tokens)-1] // Remove brackets. - mut parts, errs := parts(tokens, lex::TokenId.Comma, true) + mut parts, errs := parts(tokens, token::Id.Comma, true) mut generics := make([]&ast::TypeDecl, 0, len(parts)) self.p.errors = append(self.p.errors, errs...) for (_, mut part) in parts { @@ -344,7 +353,7 @@ impl exprBuilder { ret generics } - fn buildFnCall(mut self, mut &token: &lex::Token, mut &expr: []&lex::Token, mut &args: []&lex::Token): &ast::FnCallExpr { + fn buildFnCall(mut self, mut &token: &token::Token, mut &expr: []&token::Token, mut &args: []&token::Token): &ast::FnCallExpr { ret &ast::FnCallExpr{ Token: token, Expr: self.buildFromTokens(expr), @@ -352,9 +361,9 @@ impl exprBuilder { } } - fn buildParenthesesRange(mut self, mut &tokens: []&lex::Token): ast::ExprData { + fn buildParenthesesRange(mut self, mut &tokens: []&token::Token): ast::ExprData { mut token := tokens[0] - if token.Id == lex::TokenId.LParent { + if token.Id == token::Id.LParent { mut expr := self.tryBuildCast(tokens) if expr != nil { ret expr @@ -374,11 +383,11 @@ impl exprBuilder { ret self.buildFnCall(token, exprTokens, argsTokens) } - fn buildUnsafeExpr(mut self, mut tokens: []&lex::Token): &ast::UnsafeExpr { + fn buildUnsafeExpr(mut self, mut tokens: []&token::Token): &ast::UnsafeExpr { mut token := tokens[0] tokens = tokens[1:] // Remove unsafe keyword. mut i := 0 - mut rangeTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut rangeTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if len(rangeTokens) == 0 { self.pushErr(tokens[0], build::LogMsg.MissingExpr) ret nil @@ -389,7 +398,7 @@ impl exprBuilder { } } - fn buildAnonFn(mut self, mut &tokens: []&lex::Token): &ast::FnDecl { + fn buildAnonFn(mut self, mut &tokens: []&token::Token): &ast::FnDecl { mut f := self.p.buildFn(tokens, false, false) if !f.IsAnon() { self.pushErr(f.Token, build::LogMsg.InvalidSyntax) @@ -398,9 +407,9 @@ impl exprBuilder { ret f } - fn buildUnsafe(mut self, mut &tokens: []&lex::Token): ast::ExprData { + fn buildUnsafe(mut self, mut &tokens: []&token::Token): ast::ExprData { match tokens[1].Id { - | lex::TokenId.Fn: + | token::Id.Fn: // Unsafe anonymous function. ret self.buildAnonFn(tokens) |: @@ -408,8 +417,8 @@ impl exprBuilder { } } - fn pushRangeLitPart(mut self, mut part: []&lex::Token, - errorToken: &lex::Token, mut &parts: [][]&lex::Token) { + fn pushRangeLitPart(mut self, mut part: []&token::Token, + errorToken: &token::Token, mut &parts: [][]&token::Token) { if len(part) == 0 { self.pushErr(errorToken, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedExpr) @@ -419,29 +428,29 @@ impl exprBuilder { } // Tokens should include brace tokens. - fn getBraceRangeLitExprParts(mut self, mut tokens: []&lex::Token): [][]&lex::Token { + fn getBraceRangeLitExprParts(mut self, mut tokens: []&token::Token): [][]&token::Token { // No part. if len(tokens) < 2 { ret nil } - let mut parts: [][]&lex::Token = nil + let mut parts: [][]&token::Token = nil mut last := 0 mut rangeN := 0 tokens = tokens[1:len(tokens)-1] // Remove parentheses. for i, token in tokens { match token.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: rangeN++ - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: rangeN-- } - if rangeN > 0 || token.Id != lex::TokenId.Comma { + if rangeN > 0 || token.Id != token::Id.Comma { continue } self.pushRangeLitPart(tokens[last:i], token, parts) @@ -461,7 +470,7 @@ impl exprBuilder { ret parts } - fn buildFieldExprPair(mut self, mut tokens: []&lex::Token): &ast::FieldExprPair { + fn buildFieldExprPair(mut self, mut tokens: []&token::Token): &ast::FieldExprPair { if len(tokens)-2 == 0 { self.pushErr(tokens[1], build::LogMsg.MissingExpr) ret nil @@ -474,11 +483,11 @@ impl exprBuilder { ret pair } - fn buildStructLitExpr(mut self, mut &tokens: []&lex::Token): &ast::Expr { + fn buildStructLitExpr(mut self, mut &tokens: []&token::Token): &ast::Expr { mut token := tokens[0] - if token.Id == lex::TokenId.Ident && len(tokens) > 1 { + if token.Id == token::Id.Ident && len(tokens) > 1 { token = tokens[1] - if token.Id == lex::TokenId.Colon { + if token.Id == token::Id.Colon { ret &ast::Expr{ Token: token, End: tokens[len(tokens)-1], @@ -489,7 +498,7 @@ impl exprBuilder { ret self.buildFromTokens(tokens) } - fn buildStructLitExprs(mut self, mut &tokens: []&lex::Token): []&ast::Expr { + fn buildStructLitExprs(mut self, mut &tokens: []&token::Token): []&ast::Expr { mut parts := self.getBraceRangeLitExprParts(tokens) if len(parts) == 0 { ret nil @@ -502,7 +511,7 @@ impl exprBuilder { ret pairs } - fn buildTypedStructLiteral(mut self, mut tokens: []&lex::Token): &ast::StructLit { + fn buildTypedStructLiteral(mut self, mut tokens: []&token::Token): &ast::StructLit { mut i := 0 mut t, ok := unsafe { self.p.buildType(tokens, &i, true) } if !ok { @@ -514,7 +523,7 @@ impl exprBuilder { tokens = tokens[i:] // Remove type tokens. token := tokens[0] - if token.Id != lex::TokenId.LBrace { + if token.Id != token::Id.LBrace { self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil } @@ -526,8 +535,8 @@ impl exprBuilder { } } - fn buildBraceLitPart(mut self, mut &tokens: []&lex::Token): &ast::Expr { - mut l, mut r := splitDelim(tokens, lex::TokenId.Colon) + fn buildBraceLitPart(mut self, mut &tokens: []&token::Token): &ast::Expr { + mut l, mut r := splitDelim(tokens, token::Id.Colon) // If left is not nil, colon token found. if l != nil { ret &ast::Expr{ @@ -543,7 +552,7 @@ impl exprBuilder { ret self.buildFromTokens(tokens) } - fn buildBraceLit(mut self, mut &tokens: []&lex::Token): &ast::BraceLit { + fn buildBraceLit(mut self, mut &tokens: []&token::Token): &ast::BraceLit { mut lit := &ast::BraceLit{ Token: tokens[0], End: tokens[len(tokens)-1], @@ -562,7 +571,7 @@ impl exprBuilder { ret lit } - fn buildBraceRange(mut self, mut &tokens: []&lex::Token): ast::ExprData { + fn buildBraceRange(mut self, mut &tokens: []&token::Token): ast::ExprData { mut exprTokens, rangeN := getRangeExprTokens(tokens) match { @@ -575,7 +584,7 @@ impl exprBuilder { // Exceptional handling. elseToken := exprTokens[len(exprTokens)-1] - if exprTokens[len(exprTokens)-1].Id == lex::TokenId.Else { + if exprTokens[len(exprTokens)-1].Id == token::Id.Else { exprTokens = exprTokens[:len(exprTokens)-1] // Ignore keyword "else" mut d := self.build(exprTokens) if d == nil { @@ -585,7 +594,7 @@ impl exprBuilder { | &ast::FnCallExpr: tokens = tokens[len(exprTokens)+1:] // Get range: {...} mut i := 0 - mut rangeTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut rangeTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) mut model := (&ast::FnCallExpr)(d) if model.Ignored() { self.pushErr(elseToken, build::LogMsg.InvalidSyntax) @@ -600,12 +609,12 @@ impl exprBuilder { } match exprTokens[0].Id { - | lex::TokenId.Unsafe: + | token::Id.Unsafe: ret self.buildUnsafe(tokens) - | lex::TokenId.Fn: + | token::Id.Fn: ret self.buildAnonFn(tokens) - | lex::TokenId.Ident - | lex::TokenId.Cpp: + | token::Id.Ident + | token::Id.Cpp: ret self.buildTypedStructLiteral(tokens) |: self.pushErr(exprTokens[0], build::LogMsg.InvalidSyntax) @@ -614,14 +623,14 @@ impl exprBuilder { } // Tokens is should be store enumerable range tokens. - fn getEnumerableParts(mut self, mut tokens: []&lex::Token): [][]&lex::Token { + fn getEnumerableParts(mut self, mut tokens: []&token::Token): [][]&token::Token { tokens = tokens[1:len(tokens)-1] // Remove range tokens. - mut parts, errors := parts(tokens, lex::TokenId.Comma, true) + mut parts, errors := parts(tokens, token::Id.Comma, true) self.p.errors = append(self.p.errors, errors...) ret parts } - fn buildSlice(mut self, mut tokens: []&lex::Token): &ast::SliceExpr { + fn buildSlice(mut self, mut tokens: []&token::Token): &ast::SliceExpr { mut slc := &ast::SliceExpr{ Token: tokens[0], End: tokens[len(tokens)-1], @@ -643,8 +652,8 @@ impl exprBuilder { ret slc } - fn buildIndexing(mut self, mut exprTokens: []&lex::Token, - mut tokens: []&lex::Token, mut errorToken: &lex::Token): &ast::IndexingExpr { + fn buildIndexing(mut self, mut exprTokens: []&token::Token, + mut tokens: []&token::Token, mut errorToken: &token::Token): &ast::IndexingExpr { mut end := tokens[len(tokens)-1] tokens = tokens[1:len(tokens)-1] // Remove brackets. if len(tokens) == 0 { @@ -667,8 +676,8 @@ impl exprBuilder { } } - fn buildSlicing(mut self, mut &exprTokens: []&lex::Token, mut &start: []&lex::Token, - mut &to: []&lex::Token, mut &errorToken: &lex::Token, mut end: &lex::Token): &ast::SlicingExpr { + fn buildSlicing(mut self, mut &exprTokens: []&token::Token, mut &start: []&token::Token, + mut &to: []&token::Token, mut &errorToken: &token::Token, mut end: &token::Token): &ast::SlicingExpr { mut slc := &ast::SlicingExpr{ Token: errorToken, End: end, @@ -683,7 +692,7 @@ impl exprBuilder { ret slc } - fn buildBracketRange(mut self, mut tokens: []&lex::Token): ast::ExprData { + fn buildBracketRange(mut self, mut tokens: []&token::Token): ast::ExprData { mut errorToken := tokens[0] mut exprTokens, rangeN := getRangeExprTokens(tokens) @@ -701,14 +710,14 @@ impl exprBuilder { // Catch slicing expressions. mut splitTokens := tokens[1:len(tokens)-1] // Remove brackets. - mut start, mut to := splitDelim(splitTokens, lex::TokenId.Colon) + mut start, mut to := splitDelim(splitTokens, token::Id.Colon) if start != nil || to != nil { ret self.buildSlicing(exprTokens, start, to, errorToken, tokens[len(tokens)-1]) } ret self.buildIndexing(exprTokens, tokens, errorToken) } - fn buildExclRight(mut self, mut &tokens: []&lex::Token): ast::ExprData { + fn buildExclRight(mut self, mut &tokens: []&token::Token): ast::ExprData { token := tokens[len(tokens)-1] tokens = tokens[:len(tokens)-1] // Ignore "!" token. mut d := self.build(tokens) @@ -726,31 +735,31 @@ impl exprBuilder { ret nil } - fn buildData(mut self, mut &tokens: []&lex::Token): ast::ExprData { + fn buildData(mut self, mut &tokens: []&token::Token): ast::ExprData { match len(tokens) { | 0: ret nil | 1: ret self.buildSingle(tokens[0]) | 3: - if tokens[0].Id == lex::TokenId.Cpp { + if tokens[0].Id == token::Id.Cpp { ret self.buildBindIdent(tokens) } } mut token := tokens[len(tokens)-1] - if token.Id == lex::TokenId.TripleDot { + if token.Id == token::Id.TripleDot { ret self.buildVariadic(tokens) } token = tokens[0] // Unary operators. - if lex::IsUnaryOp(token.Id) { + if token::IsUnaryOp(token.Id) { // Handle pointer to primitive type. if len(tokens) > 1 { token = tokens[1] - if token.Id == lex::TokenId.Unsafe { + if token.Id == token::Id.Unsafe { ret self.buildType(tokens) } } @@ -759,19 +768,19 @@ impl exprBuilder { if len(tokens) >= 3 { match token.Id { - | lex::TokenId.LParent - | lex::TokenId.LBrace - | lex::TokenId.LBracket: + | token::Id.LParent + | token::Id.LBrace + | token::Id.LBracket: // Catch type casting. if len(tokens) > 3 { t := tokens[len(tokens)-1] - if t.Id == lex::TokenId.RParent { + if t.Id == token::Id.RParent { break } } next := tokens[1] - if next.Id != lex::TokenId.RBracket { + if next.Id != token::Id.RBracket { break } ret self.buildType(tokens) @@ -780,22 +789,22 @@ impl exprBuilder { token = tokens[len(tokens)-1] match token.Id { - | lex::TokenId.Ident: + | token::Id.Ident: ret self.buildSubIdent(tokens) - | lex::TokenId.Excl: + | token::Id.Excl: ret self.buildExclRight(tokens) - | lex::TokenId.RParent: + | token::Id.RParent: ret self.buildParenthesesRange(tokens) - | lex::TokenId.RBrace: + | token::Id.RBrace: ret self.buildBraceRange(tokens) - | lex::TokenId.RBracket: + | token::Id.RBracket: ret self.buildBracketRange(tokens) } self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil } - fn buildBinary(mut self, mut &tokens: []&lex::Token, i: int): ast::ExprData { + fn buildBinary(mut self, mut &tokens: []&token::Token, i: int): ast::ExprData { mut op := tokens[i] mut leftTokens := tokens[:i] if isTypeOp(op.Id) && isTypeRange(leftTokens) { @@ -820,8 +829,8 @@ impl exprBuilder { } } - fn build(mut self, mut &tokens: []&lex::Token): ast::ExprData { - if tokens[0].Id == lex::TokenId.Map { + fn build(mut self, mut &tokens: []&token::Token): ast::ExprData { + if tokens[0].Id == token::Id.Map { ret self.buildType(tokens) } i := findLowestPrecOp(tokens) @@ -831,8 +840,8 @@ impl exprBuilder { ret self.buildBinary(tokens, i) } - fn buildKind(mut self, mut &tokens: []&lex::Token): ast::ExprData { - mut parts, errors := parts(tokens, lex::TokenId.Comma, true) + fn buildKind(mut self, mut &tokens: []&token::Token): ast::ExprData { + mut parts, errors := parts(tokens, token::Id.Comma, true) if errors != nil { self.p.errors = append(self.p.errors, errors...) ret nil @@ -842,7 +851,7 @@ impl exprBuilder { ret self.build(tokens) } - fn buildFromTokens(mut self, mut tokens: []&lex::Token): &ast::Expr { + fn buildFromTokens(mut self, mut tokens: []&token::Token): &ast::Expr { if len(tokens) == 0 { ret nil } @@ -859,17 +868,17 @@ impl exprBuilder { } // Reports whether kind is potentially part of a type declaration. -fn isTypeOp(&id: lex::TokenId): bool { - ret id == lex::TokenId.Amper || - id == lex::TokenId.DblAmper || - id == lex::TokenId.Star +fn isTypeOp(&id: token::Id): bool { + ret id == token::Id.Amper || + id == token::Id.DblAmper || + id == token::Id.Star } // Reports whether range is potentially part of a type declaration. -fn isTypeRange(mut &tokens: []&lex::Token): bool { +fn isTypeRange(mut &tokens: []&token::Token): bool { mut op := false for i, token in tokens { - if token.Id == lex::TokenId.LBracket { + if token.Id == token::Id.LBracket { if op { ret true } @@ -877,10 +886,10 @@ fn isTypeRange(mut &tokens: []&lex::Token): bool { mut lTokens := tokens[i:] for _, lToken in lTokens { match lToken.Id { - | lex::TokenId.LBracket: + | token::Id.LBracket: rangeN++ continue - | lex::TokenId.RBracket: + | token::Id.RBracket: rangeN-- continue } @@ -899,16 +908,16 @@ fn isTypeRange(mut &tokens: []&lex::Token): bool { } // Returns expression tokens comes before block if exist, nil if not. -fn getBlockExpr(mut &tokens: []&lex::Token): []&lex::Token { +fn getBlockExpr(mut &tokens: []&token::Token): []&token::Token { mut braceN := 0 mut skipToNextBraceClose := 0 for i, tok in tokens { match tok.Id { - | lex::TokenId.Unsafe: - if len(tokens)-i > 1 && tokens[i+1].Id == lex::TokenId.LBrace { + | token::Id.Unsafe: + if len(tokens)-i > 1 && tokens[i+1].Id == token::Id.LBrace { skipToNextBraceClose++ } - | lex::TokenId.LBrace: + | token::Id.LBrace: if braceN > 0 || skipToNextBraceClose > 0 { if skipToNextBraceClose > 0 { skipToNextBraceClose-- @@ -917,12 +926,12 @@ fn getBlockExpr(mut &tokens: []&lex::Token): []&lex::Token { break } ret tokens[:i] - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBracket + | token::Id.LParent: braceN++ - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- } } @@ -931,32 +940,32 @@ fn getBlockExpr(mut &tokens: []&lex::Token): []&lex::Token { // Returns delimiter index, left range and right range tokens. // Returns nil slice and -1 if not found. -fn splitDelim(mut &tokens: []&lex::Token, delim: lex::TokenId): ([]&lex::Token, []&lex::Token) { +fn splitDelim(mut &tokens: []&token::Token, delim: token::Id): ([]&token::Token, []&token::Token) { mut func := -1 mut rangeN := 0 mut i := 0 for i < len(tokens); i++ { token := tokens[i] match token.Id { - | lex::TokenId.Fn: + | token::Id.Fn: func = rangeN - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: rangeN++ continue - | lex::TokenId.RParent: + | token::Id.RParent: rangeN-- if func == rangeN { func = -1 // Skip colon token if function builded. - if len(tokens)-i > 1 && tokens[i+1].Id == lex::TokenId.Colon { + if len(tokens)-i > 1 && tokens[i+1].Id == token::Id.Colon { i++ continue } } - | lex::TokenId.RBrace - | lex::TokenId.RBracket: + | token::Id.RBrace + | token::Id.RBracket: rangeN-- } if token.Id == delim && rangeN == 0 { @@ -970,7 +979,7 @@ fn splitDelim(mut &tokens: []&lex::Token, delim: lex::TokenId): ([]&lex::Token, // Finds index of priority operator and returns index of operator // if found, returns -1 if not. -fn findLowestPrecOp(&tokens: []&lex::Token): int { +fn findLowestPrecOp(&tokens: []&token::Token): int { // Set to byte.Max, there is nothing for precedence byte.Max. // It's provides optimization, avoid prec != -1 (if not setted) checking. // Always greater than actual precedences. @@ -982,19 +991,19 @@ fn findLowestPrecOp(&tokens: []&lex::Token): int { mut skipToNextBraceOpen := false for i, token in tokens { match token.Id { - | lex::TokenId.LBrace: + | token::Id.LBrace: skipToNextBraceOpen = false fall - | lex::TokenId.LParent - | lex::TokenId.LBracket: + | token::Id.LParent + | token::Id.LBracket: braceN++ continue - | lex::TokenId.RBrace - | lex::TokenId.RParent - | lex::TokenId.RBracket: + | token::Id.RBrace + | token::Id.RParent + | token::Id.RBracket: braceN-- continue - | lex::TokenId.If: + | token::Id.If: skipToNextBraceOpen = true continue } @@ -1005,22 +1014,22 @@ fn findLowestPrecOp(&tokens: []&lex::Token): int { continue | braceN > 0: continue - | !lex::IsBinOp(token.Id): + | !token::IsBinOp(token.Id): continue } left := tokens[i-1] // Skip unary operator or type annotation. - if lex::IsUnaryOp(left.Id) || left.Id == lex::TokenId.Colon { + if token::IsUnaryOp(left.Id) || left.Id == token::Id.Colon { continue } - if i > 1 && left.Id == lex::TokenId.RBracket { + if i > 1 && left.Id == token::Id.RBracket { lleft := tokens[i-2] - if lleft.Id == lex::TokenId.LBracket { + if lleft.Id == token::Id.LBracket { // Skip potential type annotations. - if token.Id == lex::TokenId.Amper || token.Id == lex::TokenId.Star { + if token.Id == token::Id.Amper || token.Id == token::Id.Star { continue } } @@ -1035,7 +1044,7 @@ fn findLowestPrecOp(&tokens: []&lex::Token): int { ret precPos } -fn buildIdentExpr(mut &token: &lex::Token): &ast::IdentExpr { +fn buildIdentExpr(mut &token: &token::Token): &ast::IdentExpr { ret &ast::IdentExpr{ Token: token, Ident: token.Kind, @@ -1043,19 +1052,19 @@ fn buildIdentExpr(mut &token: &lex::Token): &ast::IdentExpr { } } -fn getRangeExprTokens(mut &tokens: []&lex::Token): ([]&lex::Token, int) { +fn getRangeExprTokens(mut &tokens: []&token::Token): ([]&token::Token, int) { mut rangeN := 0 mut i := len(tokens) - 1 for i >= 0; i-- { tok := tokens[i] match tok.Id { - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: rangeN++ - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: rangeN-- } @@ -1066,15 +1075,15 @@ fn getRangeExprTokens(mut &tokens: []&lex::Token): ([]&lex::Token, int) { ret nil, rangeN } -fn isAnonFnHead(&tokens: []&lex::Token): bool { +fn isAnonFnHead(&tokens: []&token::Token): bool { match tokens[0].Id { - | lex::TokenId.Unsafe: - if len(tokens) == 1 || tokens[1].Id != lex::TokenId.Fn { + | token::Id.Unsafe: + if len(tokens) == 1 || tokens[1].Id != token::Id.Fn { break } fall - | lex::TokenId.Fn: - if tokens[len(tokens)-1].Id == lex::TokenId.RBrace { + | token::Id.Fn: + if tokens[len(tokens)-1].Id == token::Id.RBrace { // Not function type declaration, anonymous function expression. break } diff --git a/std/jule/parser/parse.jule b/std/jule/parser/parse.jule index df8adc7eb..7d2c2e6bc 100644 --- a/std/jule/parser/parse.jule +++ b/std/jule/parser/parse.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" // Stores information about file parsing. struct FileInfo { @@ -19,8 +19,8 @@ struct PackageInfo { // Parses fileset's tokens and builds AST. // Returns nil if f is not real. -// File should not contain comment tokens. -fn ParseFile(mut f: &lex::File): &FileInfo { +// Fileset should not contain comment tokens. +fn ParseFile(mut f: &token::Fileset): &FileInfo { if f == nil { ret nil } @@ -35,8 +35,8 @@ fn ParseFile(mut f: &lex::File): &FileInfo { // Parses fileset's tokens and builds AST. // Returns nil if filesets is nil. // Skip fileset if nil. -// Files should not contain comment tokens. -fn ParsePackage(mut filesets: []&lex::File): &PackageInfo { +// Filesets should not contain comment tokens. +fn ParsePackage(mut filesets: []&token::Fileset): &PackageInfo { if filesets == nil { ret nil } @@ -52,7 +52,7 @@ fn ParsePackage(mut filesets: []&lex::File): &PackageInfo { ret pinf } -fn parseFileset(mut f: &lex::File): (&ast::AST, []build::Log) { +fn parseFileset(mut f: &token::Fileset): (&ast::AST, []build::Log) { mut p := new(parser) p.parse(f) ret p.ast, p.errors diff --git a/std/jule/parser/parser.jule b/std/jule/parser/parser.jule index 79d092127..9b6f71c55 100644 --- a/std/jule/parser/parser.jule +++ b/std/jule/parser/parser.jule @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path -use ast for std::jule::ast -use lex for std::jule::lex -use build for std::jule::build -use mod for std::jule::internal::mod -use strings for std::strings - -fn makeErr(row: int, col: int, &f: &lex::File, fmt: build::LogMsg, args: ...any): build::Log { +use "std/fs/path" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/internal/mod" +use "std/jule/token" +use "std/strings" + +fn makeErr(row: int, col: int, &f: &token::Fileset, fmt: build::LogMsg, args: ...any): build::Log { ret build::Log{ Kind: build::LogKind.Error, Row: row, @@ -27,7 +27,7 @@ fn makeErr(row: int, col: int, &f: &lex::File, fmt: build::LogMsg, args: ...any) // Special cases are: // range(i, open, close, tokens) = nil if i > len(tokens) // range(i, open, close, tokens) = nil if tokens[i].Id != open -fn range(mut &i: int, open: lex::TokenId, close: lex::TokenId, mut &tokens: []&lex::Token): []&lex::Token { +fn range(mut &i: int, open: token::Id, close: token::Id, mut &tokens: []&token::Token): []&token::Token { if i >= len(tokens) { ret nil } @@ -57,14 +57,14 @@ fn range(mut &i: int, open: lex::TokenId, close: lex::TokenId, mut &tokens: []&l // Special cases are; // rangeLast(tokens) = tokens, nil if len(tokens) == 0 // rangeLast(tokens) = tokens, nil if tokens is not has range at last -fn rangeLast(mut &tokens: []&lex::Token): (cutted: []&lex::Token, cut: []&lex::Token) { +fn rangeLast(mut &tokens: []&token::Token): (cutted: []&token::Token, cut: []&token::Token) { if len(tokens) == 0 { ret tokens, nil } first := tokens[len(tokens)-1].Id - if first != lex::TokenId.RBrace && - first != lex::TokenId.LBracket && - first != lex::TokenId.RParent { + if first != token::Id.RBrace && + first != token::Id.LBracket && + first != token::Id.RParent { ret tokens, nil } mut braceN := 0 @@ -72,14 +72,14 @@ fn rangeLast(mut &tokens: []&lex::Token): (cutted: []&lex::Token, cut: []&lex::T for i >= 0; i-- { token := tokens[i] match token.Id { - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN++ continue - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: braceN-- } if braceN == 0 { @@ -95,7 +95,7 @@ fn rangeLast(mut &tokens: []&lex::Token): (cutted: []&lex::Token, cut: []&lex::T // // Special case is; // parts(tokens) = nil if len(tokens) == 0 -fn parts(mut &tokens: []&lex::Token, id: lex::TokenId, exprMust: bool): (parts: [][]&lex::Token, errors: []build::Log) { +fn parts(mut &tokens: []&token::Token, id: token::Id, exprMust: bool): (parts: [][]&token::Token, errors: []build::Log) { if len(tokens) == 0 { ret nil, nil } @@ -103,9 +103,9 @@ fn parts(mut &tokens: []&lex::Token, id: lex::TokenId, exprMust: bool): (parts: mut last := 0 for i, token in tokens { match token.Id { - | lex::TokenId.LBrace | lex::TokenId.LBracket | lex::TokenId.LParent: + | token::Id.LBrace | token::Id.LBracket | token::Id.LParent: rangeN++ - | lex::TokenId.RBrace | lex::TokenId.RBracket | lex::TokenId.RParent: + | token::Id.RBrace | token::Id.RBracket | token::Id.RParent: rangeN-- | id: if rangeN > 0 { @@ -125,20 +125,20 @@ fn parts(mut &tokens: []&lex::Token, id: lex::TokenId, exprMust: bool): (parts: ret } -fn getCloseOfBrace(left: lex::TokenId): lex::TokenId { +fn getCloseOfBrace(left: token::Id): token::Id { match left { - | lex::TokenId.RParent: - ret lex::TokenId.LParent - | lex::TokenId.RBrace: - ret lex::TokenId.LBrace - | lex::TokenId.RBracket: - ret lex::TokenId.LBracket + | token::Id.RParent: + ret token::Id.LParent + | token::Id.RBrace: + ret token::Id.LBrace + | token::Id.RBracket: + ret token::Id.LBracket |: ret left } } -fn compilerErr(&token: &lex::Token, &fmt: build::LogMsg, args: ...any): build::Log { +fn compilerErr(&token: &token::Token, &fmt: build::LogMsg, args: ...any): build::Log { ret build::Log{ Kind: build::LogKind.Error, Row: token.Row, @@ -166,7 +166,7 @@ impl parser { fn stopped(self): bool { ret self.ast == nil } // Appends error by specified token, key and args. - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.errors = append(self.errors, compilerErr(token, fmt, args...)) } @@ -175,11 +175,11 @@ impl parser { unsafe { pushSuggestion(&self.errors[len(self.errors)-1], fmt, args...) } } - fn buildExpr(mut &self, mut &tokens: []&lex::Token): &ast::Expr { + fn buildExpr(mut &self, mut &tokens: []&token::Token): &ast::Expr { ret self.ep.buildFromTokens(tokens) } - fn buildDirective(mut self, mut tokens: []&lex::Token): &ast::Directive { + fn buildDirective(mut self, mut tokens: []&token::Token): &ast::Directive { if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil @@ -207,7 +207,7 @@ impl parser { self.directives = append(self.directives, d) } - fn buildScope(mut &self, mut &tokens: []&lex::Token, mut end: &lex::Token): &ast::ScopeTree { + fn buildScope(mut &self, mut &tokens: []&token::Token, mut end: &token::Token): &ast::ScopeTree { mut s := newScope() s.End = end mut sp := scopeParser{ @@ -217,7 +217,7 @@ impl parser { ret s } - unsafe fn _buildType(mut &self, mut &tokens: []&lex::Token, + unsafe fn _buildType(mut &self, mut &tokens: []&token::Token, mut i: *int, err: bool): (&ast::TypeDecl, bool) { mut tb := typeBuilder{ p: self, @@ -229,7 +229,7 @@ impl parser { } // Builds AST model of data-type. - unsafe fn buildType(mut &self, mut &tokens: []&lex::Token, + unsafe fn buildType(mut &self, mut &tokens: []&token::Token, mut i: *int, err: bool): (&ast::TypeDecl, bool) { token := tokens[*i] mut t, ok := self._buildType(tokens, i, err) @@ -239,7 +239,7 @@ impl parser { ret t, ok } - fn buildTypeAliasDecl(mut &self, mut &tokens: []&lex::Token): &ast::TypeAliasDecl { + fn buildTypeAliasDecl(mut &self, mut &tokens: []&token::Token): &ast::TypeAliasDecl { mut i := 1 // Skip "type" keyword. if i >= len(tokens) { self.pushErr(tokens[i-1], build::LogMsg.InvalidSyntax) @@ -250,7 +250,7 @@ impl parser { Ident: tokens[1].Kind, } mut token := tokens[i] - if token.Id != lex::TokenId.Ident { + if token.Id != token::Id.Ident { self.pushErr(token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } @@ -260,7 +260,7 @@ impl parser { ret tad } token = tokens[i] - if token.Id != lex::TokenId.Colon { + if token.Id != token::Id.Colon { self.pushErr(tokens[i-1], build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedColon) ret tad @@ -279,12 +279,12 @@ impl parser { ret tad } - fn buildVarTypeAndExpr(mut &self, mut &v: &ast::VarDecl, mut &tokens: []&lex::Token) { + fn buildVarTypeAndExpr(mut &self, mut &v: &ast::VarDecl, mut &tokens: []&token::Token) { mut i := 0 mut tok := tokens[i] - if tok.Id == lex::TokenId.Colon { + if tok.Id == token::Id.Colon { i++ // Skip type annotation operator (:) - if i >= len(tokens) || tokens[i].Id == lex::TokenId.Eq { + if i >= len(tokens) || tokens[i].Id == token::Id.Eq { self.pushErr(tok, build::LogMsg.MissingType) ret } @@ -298,7 +298,7 @@ impl parser { } } - if tok.Id != lex::TokenId.Eq { + if tok.Id != token::Id.Eq { self.pushErr(tok, build::LogMsg.InvalidSyntax) ret } @@ -312,9 +312,9 @@ impl parser { v.Expr = self.buildExpr(exprTokens) } - fn buildVarCommon(mut &self, mut &v: &ast::VarDecl, mut tokens: []&lex::Token) { + fn buildVarCommon(mut &self, mut &v: &ast::VarDecl, mut tokens: []&token::Token) { v.Token = tokens[0] - if v.Token.Id != lex::TokenId.Ident { + if v.Token.Id != token::Id.Ident { self.pushErr(v.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret @@ -328,13 +328,13 @@ impl parser { } } - fn buildVarBegin(mut self, mut &v: &ast::VarDecl, mut &tokens: []&lex::Token) { + fn buildVarBegin(mut self, mut &v: &ast::VarDecl, mut &tokens: []&token::Token) { tok := tokens[0] match tok.Id { - | lex::TokenId.Static: + | token::Id.Static: v.Statically = true fall - | lex::TokenId.Let: + | token::Id.Let: // Initialize 1 for skip the let keyword if len(tokens) == 1 { tokens = nil @@ -342,12 +342,12 @@ impl parser { ret } tokens = tokens[1:] - if tokens[0].Id == lex::TokenId.Mut { + if tokens[0].Id == token::Id.Mut { v.Mutable = true // Skip the mut keyword tokens = tokens[1:] } - | lex::TokenId.Const: + | token::Id.Const: v.Constant = true tokens = tokens[1:] |: @@ -356,7 +356,7 @@ impl parser { } } - fn buildVar(mut &self, mut tokens: []&lex::Token): &ast::VarDecl { + fn buildVar(mut &self, mut tokens: []&token::Token): &ast::VarDecl { mut v := &ast::VarDecl{ Token: tokens[0], } @@ -364,7 +364,7 @@ impl parser { if len(tokens) == 0 { ret nil } - if tokens[0].Id == lex::TokenId.Amper { + if tokens[0].Id == token::Id.Amper { v.Reference = true if len(tokens) == 1 { ret nil @@ -375,17 +375,17 @@ impl parser { ret v } - fn buildGeneric(mut &self, mut &tokens: []&lex::Token): &ast::GenericDecl { + fn buildGeneric(mut &self, mut &tokens: []&token::Token): &ast::GenericDecl { mut g := &ast::GenericDecl{ Token: tokens[0], } - if g.Token.Id != lex::TokenId.Ident { + if g.Token.Id != token::Id.Ident { self.pushErr(g.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } g.Ident = g.Token.Kind if len(tokens) > 1 { - if tokens[1].Id != lex::TokenId.Colon { + if tokens[1].Id != token::Id.Colon { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) ret nil } @@ -394,7 +394,7 @@ impl parser { ret nil } mut constraintTokens := tokens[2:] - mut parts, errors := parts(constraintTokens, lex::TokenId.Vline, true) + mut parts, errors := parts(constraintTokens, token::Id.Vline, true) if len(errors) > 0 { self.errors = append(self.errors, errors...) ret nil @@ -412,13 +412,13 @@ impl parser { ret g } - fn buildGenerics(mut &self, mut &tokens: []&lex::Token, &errorToken: &lex::Token): []&ast::GenericDecl { + fn buildGenerics(mut &self, mut &tokens: []&token::Token, &errorToken: &token::Token): []&ast::GenericDecl { if len(tokens) == 0 { self.pushErr(errorToken, build::LogMsg.MissingExpr) ret nil } - mut parts, errors := parts(tokens, lex::TokenId.Comma, true) + mut parts, errors := parts(tokens, token::Id.Comma, true) if len(errors) > 0 { self.errors = append(self.errors, errors...) ret nil @@ -432,7 +432,7 @@ impl parser { ret generics } - fn buildSelfParam(mut self, mut tokens: []&lex::Token): &ast::ParamDecl { + fn buildSelfParam(mut self, mut tokens: []&token::Token): &ast::ParamDecl { if len(tokens) == 0 { ret nil } @@ -440,7 +440,7 @@ impl parser { mut param := new(ast::ParamDecl) // Detects mut keyword. - if tokens[0].Id == lex::TokenId.Mut { + if tokens[0].Id == token::Id.Mut { param.Mutable = true if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) @@ -449,10 +449,10 @@ impl parser { tokens = tokens[1:] } - mut ident := strings::StrBuilder.New(5) + mut ident := strings::Builder.New(5) - if tokens[0].Id == lex::TokenId.Amper { - ident.WriteStr(lex::TokenKind.Amper) + if tokens[0].Id == token::Id.Amper { + ident.WriteStr(token::Kind.Amper) if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil @@ -460,8 +460,8 @@ impl parser { tokens = tokens[1:] } - if tokens[0].Id == lex::TokenId.Self { - ident.WriteStr(lex::TokenKind.Self) + if tokens[0].Id == token::Id.Self { + ident.WriteStr(token::Kind.Self) param.Token = tokens[0] if len(tokens) != 1 { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) @@ -472,10 +472,10 @@ impl parser { ret param } - fn paramTypeBegin(mut self, mut ¶m: &ast::ParamDecl, mut &i: int, &tokens: []&lex::Token) { + fn paramTypeBegin(mut self, mut ¶m: &ast::ParamDecl, mut &i: int, &tokens: []&token::Token) { for i < len(tokens); i++ { token := tokens[i] - if token.Id != lex::TokenId.TripleDot { + if token.Id != token::Id.TripleDot { ret } @@ -487,7 +487,7 @@ impl parser { } } - fn buildParamType(mut &self, mut ¶m: &ast::ParamDecl, mut &tokens: []&lex::Token) { + fn buildParamType(mut &self, mut ¶m: &ast::ParamDecl, mut &tokens: []&token::Token) { mut i := 0 self.paramTypeBegin(param, i, tokens) if i >= len(tokens) { @@ -500,7 +500,7 @@ impl parser { } } - fn buildParamBody(mut &self, mut ¶m: &ast::ParamDecl, mut tokens: []&lex::Token) { + fn buildParamBody(mut &self, mut ¶m: &ast::ParamDecl, mut tokens: []&token::Token) { mut tok := tokens[0] if len(tokens) == 1 { // Just identifier token. @@ -510,8 +510,8 @@ impl parser { self.pushErr(tok, build::LogMsg.MissingType) ret } - if tokens[1].Id != lex::TokenId.Colon { - param.Ident = lex::Ident.Anon + if tokens[1].Id != token::Id.Colon { + param.Ident = token::Ident.Anon self.buildParamType(param, tokens) ret } @@ -520,13 +520,13 @@ impl parser { self.buildParamType(param, tokens) } - fn buildParam(mut &self, mut tokens: []&lex::Token): &ast::ParamDecl { + fn buildParam(mut &self, mut tokens: []&token::Token): &ast::ParamDecl { mut param := &ast::ParamDecl{ Token: tokens[0], } // Detects mut keyword. - if param.Token.Id == lex::TokenId.Mut { + if param.Token.Id == token::Id.Mut { param.Mutable = true if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) @@ -538,13 +538,13 @@ impl parser { // Catch reference parameters. if len(tokens) >= 3 { - if param.Token.Id == lex::TokenId.Amper { + if param.Token.Id == token::Id.Amper { if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil } - if tokens[1].Id == lex::TokenId.Ident && tokens[2].Id == lex::TokenId.Colon { + if tokens[1].Id == token::Id.Ident && tokens[2].Id == token::Id.Colon { param.Reference = true tokens = tokens[1:] param.Token = tokens[0] @@ -552,9 +552,9 @@ impl parser { } } - if param.Token.Id != lex::TokenId.Ident { + if param.Token.Id != token::Id.Ident { // Just data type - param.Ident = lex::Ident.Anon + param.Ident = token::Ident.Anon self.buildParamType(param, tokens) } else { self.buildParamBody(param, tokens) @@ -578,13 +578,13 @@ impl parser { Ident: param.Token.Kind, }, } - param.Ident = lex::Ident.Anon + param.Ident = token::Ident.Anon } } } - fn buildParams(mut &self, mut &tokens: []&lex::Token, method: bool): []&ast::ParamDecl { - mut parts, errs := parts(tokens, lex::TokenId.Comma, true) + fn buildParams(mut &self, mut &tokens: []&token::Token, method: bool): []&ast::ParamDecl { + mut parts, errs := parts(tokens, token::Id.Comma, true) self.errors = append(self.errors, errs...) if len(parts) == 0 { ret nil @@ -613,7 +613,7 @@ impl parser { ret params } - fn buildMultiRetType(mut &self, mut &tokens: []&lex::Token, mut &i: int): (t: &ast::RetTypeDecl, ok: bool) { + fn buildMultiRetType(mut &self, mut &tokens: []&token::Token, mut &i: int): (t: &ast::RetTypeDecl, ok: bool) { t = new(ast::RetTypeDecl) i++ if i >= len(tokens) { @@ -623,16 +623,16 @@ impl parser { } i-- // For point to parentheses - ( - - mut rangeTokens := range(i, lex::TokenId.LParent, lex::TokenId.RParent, tokens) + mut rangeTokens := range(i, token::Id.LParent, token::Id.RParent, tokens) - mut parts, errs := parts(rangeTokens, lex::TokenId.Comma, true) + mut parts, errs := parts(rangeTokens, token::Id.Comma, true) self.errors = append(self.errors, errs...) if len(parts) == 0 { ret } mut types := make([]&ast::TypeDecl, 0, len(parts)) - t.Idents = make([]&lex::Token, 0, len(parts)) + t.Idents = make([]&token::Token, 0, len(parts)) for (_, mut part) in parts { if len(part) == 0 { continue @@ -643,7 +643,7 @@ impl parser { // Check type annotation. if len(part) > 1 { token = part[1] - if token.Id == lex::TokenId.Colon { + if token.Id == token::Id.Colon { offset = 2 if len(part) < 3 { self.pushErr(token, build::LogMsg.MissingType) @@ -654,8 +654,8 @@ impl parser { token = part[0] if offset != 2 { - mut newToken := new(lex::Token, *token) - newToken.Kind = lex::Ident.Anon + mut newToken := new(token::Token, *token) + newToken.Kind = token::Ident.Anon t.Idents = append(t.Idents, newToken) } else { t.Idents = append(t.Idents, token) @@ -684,7 +684,7 @@ impl parser { } // Builds function return type from tokens. - fn buildRetType(mut &self, mut &tokens: []&lex::Token, mut &i: int): (t: &ast::RetTypeDecl, ok: bool) { + fn buildRetType(mut &self, mut &tokens: []&token::Token, mut &i: int): (t: &ast::RetTypeDecl, ok: bool) { t = new(ast::RetTypeDecl) if i >= len(tokens) { ret @@ -692,11 +692,11 @@ impl parser { mut token := tokens[i] match token.Id { - | lex::TokenId.LBrace: + | token::Id.LBrace: ret - | lex::TokenId.Eq: + | token::Id.Eq: ret - | lex::TokenId.Colon: + | token::Id.Colon: if i+1 >= len(tokens) { self.pushErr(token, build::LogMsg.MissingType) ret @@ -705,10 +705,10 @@ impl parser { i++ token = tokens[i] match token.Id { - | lex::TokenId.LParent: + | token::Id.LParent: t, ok = self.buildMultiRetType(tokens, i) ret - | lex::TokenId.LBrace: + | token::Id.LBrace: self.pushErr(token, build::LogMsg.MissingType) ret } @@ -723,13 +723,13 @@ impl parser { // Build function prototype. // Body is not necessary for successfull parsing. // Just declration. - fn buildFnPrototype(mut &self, mut &tokens: []&lex::Token, mut &i: int, method: bool): &ast::FnDecl { + fn buildFnPrototype(mut &self, mut &tokens: []&token::Token, mut &i: int, method: bool): &ast::FnDecl { mut f := &ast::FnDecl{ Token: tokens[i], } // Detect static keyword. - if f.Token.Id == lex::TokenId.Static { + if f.Token.Id == token::Id.Static { f.Statically = true i++ if i >= len(tokens) { @@ -740,7 +740,7 @@ impl parser { } // Detect unsafe keyword. - if f.Token.Id == lex::TokenId.Unsafe { + if f.Token.Id == token::Id.Unsafe { f.Unsafety = true i++ if i >= len(tokens) { @@ -758,7 +758,7 @@ impl parser { } tok := tokens[i] - if tok.Id == lex::TokenId.Ident { + if tok.Id == token::Id.Ident { i++ if i >= len(tokens) { self.pushErr(f.Token, build::LogMsg.InvalidSyntax) @@ -766,28 +766,28 @@ impl parser { } f.Ident = tok.Kind } else { - f.Ident = lex::Ident.Anon + f.Ident = token::Ident.Anon } errorToken := tokens[i] - mut genericsTokens := range(i, lex::TokenId.LBracket, lex::TokenId.RBracket, tokens) + mut genericsTokens := range(i, token::Id.LBracket, token::Id.RBracket, tokens) if genericsTokens != nil { f.Generics = self.buildGenerics(genericsTokens, errorToken) } - if tokens[i].Id != lex::TokenId.LParent { + if tokens[i].Id != token::Id.LParent { self.pushErr(tokens[i], build::LogMsg.MissingFnParentheses) ret nil } - mut paramsToks := range(i, lex::TokenId.LParent, lex::TokenId.RParent, tokens) + mut paramsToks := range(i, token::Id.LParent, token::Id.RParent, tokens) if len(paramsToks) > 0 { f.Params = self.buildParams(paramsToks, method) } if i < len(tokens) { token := tokens[i] - if token.Id == lex::TokenId.Excl { + if token.Id == token::Id.Excl { f.Exceptional = true i++ } @@ -800,7 +800,7 @@ impl parser { // Parses function define. // Prototype and body. - fn buildFn(mut &self, mut &tokens: []&lex::Token, method: bool, prototype: bool): &ast::FnDecl { + fn buildFn(mut &self, mut &tokens: []&token::Token, method: bool, prototype: bool): &ast::FnDecl { mut i := 0 mut f := self.buildFnPrototype(tokens, i, method) if prototype { @@ -818,7 +818,7 @@ impl parser { self.pushSuggestion(build::LogMsg.ExpectedBody) ret nil } - mut blockTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut blockTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if blockTokens != nil { f.Scope = self.buildScope(blockTokens, tokens[i-1]) f.Scope.Unsafety = f.Unsafety @@ -834,200 +834,49 @@ impl parser { ret f } - fn getUseDeclSelectors(mut self, mut tokens: []&lex::Token): []&lex::Token { - mut i := 0 - tokens = range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) - mut parts, errs := parts(tokens, lex::TokenId.Comma, true) - if len(errs) > 0 { - self.errors = append(self.errors, errs...) - ret nil - } - - mut selectors := make([]&lex::Token, 0, len(parts)) - for (_, mut part) in parts { - if len(part) > 1 { - self.pushErr(part[1], build::LogMsg.InvalidSyntax) - } - mut tok := part[0] - if tok.Id != lex::TokenId.Ident && tok.Id != lex::TokenId.Self { - self.pushErr(tok, build::LogMsg.InvalidSyntax) - self.pushSuggestion(build::LogMsg.ExpectedIdentifier) - continue - } - selectors = append(selectors, tok) - } - ret selectors - } - - fn buildBindUseDecl(mut self, mut &decl: &ast::UseDecl, &tokens: []&lex::Token) { + fn buildBindUseDecl(mut self, mut &decl: &ast::UseDecl, mut &tokens: []&token::Token) { if len(tokens) > 1 { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) } - token := tokens[0] - if token.Id != lex::TokenId.Lit || (token.Kind[0] != '`' && token.Kind[0] != '"') { + mut token := tokens[0] + if token.Id != token::Id.Lit || !token::IsStr(token.Kind) { self.pushErr(token, build::LogMsg.InvalidExpr) ret } decl.Binded = true - decl.LinkPath = token.Kind[1:len(token.Kind)-1] - } - - fn useDeclTokstoa(mut self, &tokens: []&lex::Token): str { - mut n := 0 - for _, token in tokens { - if token.Id != lex::TokenId.Ident && token.Id != lex::TokenId.DblColon { - self.pushErr(token, build::LogMsg.InvalidSyntax) - } - n += len(token.Kind) - } - mut s := strings::StrBuilder.New(n) - for _, token in tokens { - s.WriteStr(token.Kind) - } - ret s.Str() - } - - fn buildStdUseDecl(mut self, mut &decl: &ast::UseDecl, mut tokens: []&lex::Token) { - decl.Std = true - - mut token := tokens[0] - if len(tokens) < 3 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - - tokens = tokens[2:] - token = tokens[len(tokens)-1] - match token.Id { - | lex::TokenId.DblColon: - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - | lex::TokenId.RBrace: - let mut selectors: []&lex::Token = nil - tokens, selectors = rangeLast(tokens) - decl.Selected = self.getUseDeclSelectors(selectors) - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - token = tokens[len(tokens)-1] - if token.Id != lex::TokenId.DblColon { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - tokens = tokens[:len(tokens)-1] - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - | lex::TokenId.Star: - tokens = tokens[:len(tokens)-1] - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - token = tokens[len(tokens)-1] - if token.Id != lex::TokenId.DblColon { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - tokens = tokens[:len(tokens)-1] - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - decl.Full = true - } - if len(tokens) == 1 && tokens[0].Id == lex::TokenId.Unsafe { // Is std::unsafe? - decl.LinkPath = "std::unsafe" - } else { - decl.LinkPath = "std::" + self.useDeclTokstoa(tokens) - } + decl.Path = token } - fn buildIdentUseDecl(mut self, mut &decl: &ast::UseDecl, mut tokens: []&lex::Token) { - decl.Std = false - - mut token := tokens[len(tokens)-1] - match token.Id { - | lex::TokenId.DblColon: - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - | lex::TokenId.RBrace: - let mut selectors: []&lex::Token = nil - tokens, selectors = rangeLast(tokens) - decl.Selected = self.getUseDeclSelectors(selectors) - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - token = tokens[len(tokens)-1] - if token.Id != lex::TokenId.DblColon { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - tokens = tokens[:len(tokens)-1] - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - | lex::TokenId.Star: - tokens = tokens[:len(tokens)-1] - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - token = tokens[len(tokens)-1] - if token.Id != lex::TokenId.DblColon { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - tokens = tokens[:len(tokens)-1] - if len(tokens) == 0 { - self.pushErr(token, build::LogMsg.InvalidSyntax) - ret - } - decl.Full = true - } - - decl.LinkPath = self.useDeclTokstoa(tokens) - } - - fn parseUseDecl(mut self, mut &decl: &ast::UseDecl, mut tokens: []&lex::Token) { + fn parseUseDecl(mut self, mut &decl: &ast::UseDecl, mut tokens: []&token::Token) { if decl.Binded { self.buildBindUseDecl(decl, tokens) ret } mut token := tokens[0] - if token.Id != lex::TokenId.Ident { + if token.Id != token::Id.Ident && token.Id != token::Id.Lit && !token::IsStr(token.Kind) { self.pushErr(token, build::LogMsg.InvalidSyntax) - self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret } - if len(tokens) > 2 && tokens[1].Id == lex::TokenId.For { - decl.Alias = token.Kind - if tokens[2].Id != lex::TokenId.Ident { + if token.Id == token::Id.Ident { // custom alias exist + decl.Alias = token + tokens = tokens[1:] + if len(tokens) == 0 { self.pushErr(token, build::LogMsg.InvalidSyntax) - self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret } - tokens = tokens[2:] token = tokens[0] + if token.Id != token::Id.Lit || !token::IsStr(token.Kind) { + self.pushErr(token, build::LogMsg.InvalidSyntax) + ret + } } - const StdlibPrefix = "std" - - match { - | token.Kind == StdlibPrefix: - self.buildStdUseDecl(decl, tokens) - |: - self.buildIdentUseDecl(decl, tokens) - } + decl.Path = token } - fn buildUseDecl(mut self, mut tokens: []&lex::Token, binded: bool): &ast::UseDecl { + fn buildUseDecl(mut self, mut tokens: []&token::Token, binded: bool): &ast::UseDecl { mut decl := &ast::UseDecl{ Token: tokens[0], // See developer reference (9). Binded: binded, @@ -1041,28 +890,28 @@ impl parser { ret decl } - fn buildTypeEnumItemKind(mut &self, mut &i: int, mut &tokens: []&lex::Token): &ast::TypeDecl { + fn buildTypeEnumItemKind(mut &self, mut &i: int, mut &tokens: []&token::Token): &ast::TypeDecl { mut braceN := 0 exprStart := i for i < len(tokens); i++ { t := tokens[i] match t.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: braceN++ continue - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- } if braceN > 0 { continue } - if t.Id == lex::TokenId.Comma || i+1 >= len(tokens) { - let mut kindTokens: []&lex::Token = nil - if t.Id == lex::TokenId.Comma { + if t.Id == token::Id.Comma || i+1 >= len(tokens) { + let mut kindTokens: []&token::Token = nil + if t.Id == token::Id.Comma { kindTokens = tokens[exprStart:i] } else { kindTokens = tokens[exprStart:] @@ -1078,19 +927,19 @@ impl parser { ret nil } - fn buildTypeEnumItems(mut &self, mut &tokens: []&lex::Token): []&ast::TypeEnumItemDecl { + fn buildTypeEnumItems(mut &self, mut &tokens: []&token::Token): []&ast::TypeEnumItemDecl { mut items := make([]&ast::TypeEnumItemDecl, 0, 1) mut i := 0 for i < len(tokens); i++ { mut t := tokens[i] mut item := new(ast::TypeEnumItemDecl) item.Token = t - if item.Token.Id == lex::TokenId.Ident && len(tokens)-i > 2 { + if item.Token.Id == token::Id.Ident && len(tokens)-i > 2 { t = tokens[i+1] - if t.Id == lex::TokenId.Colon { + if t.Id == token::Id.Colon { item.Ident = item.Token.Kind i += 2 - if i >= len(tokens) || tokens[i].Id == lex::TokenId.Comma { + if i >= len(tokens) || tokens[i].Id == token::Id.Comma { self.pushErr(t, build::LogMsg.MissingType) continue } @@ -1102,19 +951,19 @@ impl parser { ret items } - fn buildTypeEnumDecl(mut &self, mut &tokens: []&lex::Token): &ast::TypeEnumDecl { + fn buildTypeEnumDecl(mut &self, mut &tokens: []&token::Token): &ast::TypeEnumDecl { mut i := 1 mut e := &ast::TypeEnumDecl{ // Skip "enum" tokens. Token: tokens[i], } - if e.Token.Id != lex::TokenId.Ident { + if e.Token.Id != token::Id.Ident { self.pushErr(e.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } e.Ident = e.Token.Kind i += 3 // Skip "identifier: type" tokens. - mut itemTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut itemTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if itemTokens == nil { self.stop() self.pushErr(e.Token, build::LogMsg.BodyNotExist) @@ -1129,28 +978,28 @@ impl parser { ret e } - fn buildEnumItemExpr(mut &self, mut &i: int, mut &tokens: []&lex::Token): &ast::Expr { + fn buildEnumItemExpr(mut &self, mut &i: int, mut &tokens: []&token::Token): &ast::Expr { mut braceN := 0 exprStart := i for i < len(tokens); i++ { t := tokens[i] match t.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: braceN++ continue - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- } if braceN > 0 { continue } - if t.Id == lex::TokenId.Comma || i+1 >= len(tokens) { - let mut exprTokens: []&lex::Token = nil - if t.Id == lex::TokenId.Comma { + if t.Id == token::Id.Comma || i+1 >= len(tokens) { + let mut exprTokens: []&token::Token = nil + if t.Id == token::Id.Comma { exprTokens = tokens[exprStart:i] } else { exprTokens = tokens[exprStart:] @@ -1161,19 +1010,19 @@ impl parser { ret nil } - fn buildEnumItems(mut &self, mut &tokens: []&lex::Token): []&ast::EnumItemDecl { + fn buildEnumItems(mut &self, mut &tokens: []&token::Token): []&ast::EnumItemDecl { mut items := make([]&ast::EnumItemDecl, 0, 1) mut i := 0 for i < len(tokens); i++ { mut t := tokens[i] mut item := new(ast::EnumItemDecl) item.Token = t - if item.Token.Id != lex::TokenId.Ident { + if item.Token.Id != token::Id.Ident { self.pushErr(item.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } item.Ident = item.Token.Kind - if i+1 >= len(tokens) || tokens[i+1].Id == lex::TokenId.Comma { + if i+1 >= len(tokens) || tokens[i+1].Id == token::Id.Comma { if i+1 < len(tokens) { i++ } @@ -1183,12 +1032,12 @@ impl parser { i++ t = tokens[i] i++ - if t.Id != lex::TokenId.Colon { + if t.Id != token::Id.Colon { self.pushErr(t, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedColonForAssign) continue } - if i >= len(tokens) || tokens[i].Id == lex::TokenId.Comma { + if i >= len(tokens) || tokens[i].Id == token::Id.Comma { self.pushErr(t, build::LogMsg.MissingExpr) continue } @@ -1198,7 +1047,7 @@ impl parser { ret items } - fn buildEnumDecl(mut &self, mut &tokens: []&lex::Token): &ast::EnumDecl { + fn buildEnumDecl(mut &self, mut &tokens: []&token::Token): &ast::EnumDecl { if len(tokens) < 3 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil @@ -1206,13 +1055,13 @@ impl parser { mut e := &ast::EnumDecl{ Token: tokens[1], } - if e.Token.Id != lex::TokenId.Ident { + if e.Token.Id != token::Id.Ident { self.pushErr(e.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } e.Ident = e.Token.Kind mut i := 2 - if tokens[i].Id == lex::TokenId.Colon { + if tokens[i].Id == token::Id.Colon { i++ if i >= len(tokens) { self.pushErr(tokens[i-1], build::LogMsg.InvalidSyntax) @@ -1228,7 +1077,7 @@ impl parser { } else { e.Kind = nil } - mut itemTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut itemTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if itemTokens == nil { self.stop() self.pushErr(e.Token, build::LogMsg.BodyNotExist) @@ -1243,19 +1092,19 @@ impl parser { ret e } - fn buildNodeEnumDecl(mut &self, mut &tokens: []&lex::Token): ast::NodeData { - if len(tokens) > 3 && tokens[2].Id == lex::TokenId.Colon { - if tokens[3].Id == lex::TokenId.Type { + fn buildNodeEnumDecl(mut &self, mut &tokens: []&token::Token): ast::NodeData { + if len(tokens) > 3 && tokens[2].Id == token::Id.Colon { + if tokens[3].Id == token::Id.Type { ret self.buildTypeEnumDecl(tokens) } } ret self.buildEnumDecl(tokens) } - fn buildField(mut &self, mut tokens: []&lex::Token): &ast::FieldDecl { + fn buildField(mut &self, mut tokens: []&token::Token): &ast::FieldDecl { mut f := new(ast::FieldDecl) - f.Mutable = tokens[0].Id == lex::TokenId.Mut + f.Mutable = tokens[0].Id == token::Id.Mut if f.Mutable { if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) @@ -1265,7 +1114,7 @@ impl parser { } f.Token = tokens[0] - if f.Token.Id != lex::TokenId.Ident { + if f.Token.Id != token::Id.Ident { self.pushErr(f.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret nil @@ -1275,7 +1124,7 @@ impl parser { if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.MissingType) ret nil - } else if len(tokens) < 3 || tokens[1].Id != lex::TokenId.Colon { + } else if len(tokens) < 3 || tokens[1].Id != token::Id.Colon { self.pushErr(tokens[1], build::LogMsg.MissingType) ret nil } @@ -1285,7 +1134,7 @@ impl parser { f.Kind, _ = unsafe { self.buildType(tokens, &i, true) } if i < len(tokens) { token := tokens[i] - if token.Id != lex::TokenId.Eq { + if token.Id != token::Id.Eq { self.pushErr(tokens[i], build::LogMsg.InvalidSyntax) ret nil } @@ -1301,7 +1150,7 @@ impl parser { ret f } - fn buildStructDeclFields(mut &self, mut tokens: []&lex::Token): []&ast::FieldDecl { + fn buildStructDeclFields(mut &self, mut tokens: []&token::Token): []&ast::FieldDecl { let mut fields: []&ast::FieldDecl = nil mut stmts := splitStmts(tokens) for (_, mut stmt) in stmts { @@ -1312,7 +1161,7 @@ impl parser { ret fields } - fn buildStructDecl(mut &self, mut &tokens: []&lex::Token): &ast::StructDecl { + fn buildStructDecl(mut &self, mut &tokens: []&token::Token): &ast::StructDecl { if len(tokens) < 3 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil @@ -1322,7 +1171,7 @@ impl parser { mut s := &ast::StructDecl{ Token: tokens[i], } - if s.Token.Id != lex::TokenId.Ident { + if s.Token.Id != token::Id.Ident { self.pushErr(s.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } @@ -1334,7 +1183,7 @@ impl parser { s.Ident = s.Token.Kind errorToken := tokens[i] - mut genericsTokens := range(i, lex::TokenId.LBracket, lex::TokenId.RBracket, tokens) + mut genericsTokens := range(i, token::Id.LBracket, token::Id.RBracket, tokens) if genericsTokens != nil { s.Generics = self.buildGenerics(genericsTokens, errorToken) } @@ -1344,7 +1193,7 @@ impl parser { ret s } - mut bodyTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut bodyTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if bodyTokens == nil { self.stop() self.pushErr(s.Token, build::LogMsg.BodyNotExist) @@ -1379,7 +1228,7 @@ impl parser { } } - fn buildTraitBody(mut &self, mut &t: &ast::TraitDecl, mut tokens: []&lex::Token) { + fn buildTraitBody(mut &self, mut &t: &ast::TraitDecl, mut tokens: []&token::Token) { mut stmts := splitStmts(tokens) for (_, mut stmt) in stmts { tokens = stmt.tokens @@ -1387,7 +1236,7 @@ impl parser { continue } match tokens[0].Id { - | lex::TokenId.Fn: + | token::Id.Fn: mut f := self.buildFn(tokens, true, true) if f == nil { break @@ -1411,7 +1260,7 @@ impl parser { } } - fn buildTraitDecl(mut &self, mut &tokens: []&lex::Token): &ast::TraitDecl { + fn buildTraitDecl(mut &self, mut &tokens: []&token::Token): &ast::TraitDecl { if len(tokens) < 3 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil @@ -1419,13 +1268,13 @@ impl parser { mut t := &ast::TraitDecl{ Token: tokens[1], } - if t.Token.Id != lex::TokenId.Ident { + if t.Token.Id != token::Id.Ident { self.pushErr(t.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } t.Ident = t.Token.Kind mut i := 2 - mut bodyTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut bodyTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if bodyTokens == nil { self.stop() self.pushErr(t.Token, build::LogMsg.BodyNotExist) @@ -1441,7 +1290,7 @@ impl parser { ret t } - fn buildBindFn(mut &self, mut tokens: []&lex::Token): &ast::FnDecl { + fn buildBindFn(mut &self, mut tokens: []&token::Token): &ast::FnDecl { tokens = tokens[1:] // Remove "cpp" keyword. mut f := self.buildFn(tokens, false, true) if f != nil { @@ -1451,7 +1300,7 @@ impl parser { ret f } - fn buildBindVar(mut &self, mut tokens: []&lex::Token): &ast::VarDecl { + fn buildBindVar(mut &self, mut tokens: []&token::Token): &ast::VarDecl { tokens = tokens[1:] // Remove "cpp" keyword. mut v := self.buildVar(tokens) if v != nil { @@ -1464,7 +1313,7 @@ impl parser { ret v } - fn buildBindStruct(mut &self, mut tokens: []&lex::Token): &ast::StructDecl { + fn buildBindStruct(mut &self, mut tokens: []&token::Token): &ast::StructDecl { tokens = tokens[1:] // Remove "cpp" keyword. mut s := self.buildStructDecl(tokens) if s != nil { @@ -1478,7 +1327,7 @@ impl parser { ret s } - fn buildBindTypeAlias(mut &self, mut tokens: []&lex::Token): &ast::TypeAliasDecl { + fn buildBindTypeAlias(mut &self, mut tokens: []&token::Token): &ast::TypeAliasDecl { tokens = tokens[1:] // Remove "cpp" keyword. mut t := self.buildTypeAliasDecl(tokens) if t != nil { @@ -1488,7 +1337,7 @@ impl parser { ret t } - fn buildBindUse(mut &self, mut tokens: []&lex::Token): &ast::UseDecl { + fn buildBindUse(mut &self, mut tokens: []&token::Token): &ast::UseDecl { if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.InvalidSyntax) ret nil @@ -1499,7 +1348,7 @@ impl parser { ret self.buildUseDecl(tokens, Binded) } - fn buildBind(mut &self, mut &tokens: []&lex::Token): ast::NodeData { + fn buildBind(mut &self, mut &tokens: []&token::Token): ast::NodeData { mut token := tokens[0] if len(tokens) == 1 { self.pushErr(token, build::LogMsg.InvalidSyntax) @@ -1507,15 +1356,15 @@ impl parser { } token = tokens[1] match token.Id { - | lex::TokenId.Fn - | lex::TokenId.Unsafe: + | token::Id.Fn + | token::Id.Unsafe: ret self.buildBindFn(tokens) - | lex::TokenId.Const - | lex::TokenId.Let: + | token::Id.Const + | token::Id.Let: ret self.buildBindVar(tokens) - | lex::TokenId.Struct: + | token::Id.Struct: ret self.buildBindStruct(tokens) - | lex::TokenId.Type: + | token::Id.Type: ret self.buildBindTypeAlias(tokens) |: self.pushErr(token, build::LogMsg.InvalidSyntax) @@ -1523,10 +1372,10 @@ impl parser { ret nil } - fn getMethod(mut &self, mut &tokens: []&lex::Token): &ast::FnDecl { + fn getMethod(mut &self, mut &tokens: []&token::Token): &ast::FnDecl { mut i := 0 mut token := tokens[i] - if token.Id == lex::TokenId.Static { + if token.Id == token::Id.Static { if i+1 >= len(tokens) { self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil @@ -1535,7 +1384,7 @@ impl parser { token = tokens[i] } - if token.Id == lex::TokenId.Unsafe { + if token.Id == token::Id.Unsafe { if i+1 >= len(tokens) { self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil @@ -1544,7 +1393,7 @@ impl parser { token = tokens[i] } - if token.Id != lex::TokenId.Fn { + if token.Id != token::Id.Fn { self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil } @@ -1552,26 +1401,26 @@ impl parser { ret self.buildFn(tokens, true, false) } - fn parseImplBody(mut &self, mut &ipl: &ast::Impl, mut &tokens: []&lex::Token) { + fn parseImplBody(mut &self, mut &ipl: &ast::Impl, mut &tokens: []&token::Token) { mut stmts := splitStmts(tokens) for (_, mut stmt) in stmts { tokens = stmt.tokens mut token := tokens[0] match token.Id { - | lex::TokenId.Hash: + | token::Id.Hash: self.pushDirective(self.buildDirective(tokens)) continue } match token.Id { - | lex::TokenId.Const: + | token::Id.Const: mut v := self.buildVar(tokens) if v != nil { ipl.Statics = append(ipl.Statics, v) } - | lex::TokenId.Static - | lex::TokenId.Fn - | lex::TokenId.Unsafe: + | token::Id.Static + | token::Id.Fn + | token::Id.Unsafe: mut f := self.getMethod(tokens) if f != nil { self.checkMethodReceiver(f) @@ -1585,7 +1434,7 @@ impl parser { } } - fn buildImpl(mut &self, mut tokens: []&lex::Token): &ast::Impl { + fn buildImpl(mut &self, mut tokens: []&token::Token): &ast::Impl { mut token := tokens[0] if len(tokens) < 2 { self.pushErr(token, build::LogMsg.InvalidSyntax) @@ -1608,8 +1457,8 @@ impl parser { } token = tokens[i] - if token.Id != lex::TokenId.For { - if token.Id == lex::TokenId.LBrace { + if token.Id != token::Id.For { + if token.Id == token::Id.LBrace { // This implementation is single. // Just implements to destination. // Therefore, swap Base and Dest tokens. @@ -1641,7 +1490,7 @@ impl parser { } body: - mut bodyTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut bodyTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if bodyTokens == nil { self.stop() self.pushErr(token, build::LogMsg.BodyNotExist) @@ -1656,32 +1505,32 @@ impl parser { ret ipl } - fn buildNodeData(mut &self, mut &tokens: []&lex::Token): ast::NodeData { + fn buildNodeData(mut &self, mut &tokens: []&token::Token): ast::NodeData { mut token := tokens[0] match token.Id { - | lex::TokenId.Fn - | lex::TokenId.Unsafe: + | token::Id.Fn + | token::Id.Unsafe: mut f := self.buildFn(tokens, false, false) if f != nil { f.Global = true } ret f - | lex::TokenId.Let - | lex::TokenId.Const - | lex::TokenId.Mut - | lex::TokenId.Static: + | token::Id.Let + | token::Id.Const + | token::Id.Mut + | token::Id.Static: ret self.buildVar(tokens) - | lex::TokenId.Type: + | token::Id.Type: ret self.buildTypeAliasDecl(tokens) - | lex::TokenId.Enum: + | token::Id.Enum: ret self.buildNodeEnumDecl(tokens) - | lex::TokenId.Struct: + | token::Id.Struct: ret self.buildStructDecl(tokens) - | lex::TokenId.Trait: + | token::Id.Trait: ret self.buildTraitDecl(tokens) - | lex::TokenId.Impl: + | token::Id.Impl: ret self.buildImpl(tokens) - | lex::TokenId.Cpp: + | token::Id.Cpp: ret self.buildBind(tokens) |: self.pushErr(token, build::LogMsg.InvalidSyntax) @@ -1727,27 +1576,27 @@ impl parser { } } - fn pushMetaNodes(mut &self, mut &tokens: []&lex::Token): bool { + fn pushMetaNodes(mut &self, mut &tokens: []&token::Token): bool { match tokens[0].Id { - | lex::TokenId.Use: + | token::Id.Use: const Binded = false mut decl := self.buildUseDecl(tokens, Binded) self.pushUseDecl(decl) ret true - | lex::TokenId.Cpp: - if len(tokens) > 1 && tokens[1].Id == lex::TokenId.Use { + | token::Id.Cpp: + if len(tokens) > 1 && tokens[1].Id == token::Id.Use { mut decl := self.buildBindUse(tokens) self.pushUseDecl(decl) ret true } - | lex::TokenId.Hash: + | token::Id.Hash: self.pushDirective(self.buildDirective(tokens)) ret true } ret false } - fn parseNode(mut &self, mut &st: []&lex::Token): ast::Node { + fn parseNode(mut &self, mut &st: []&token::Token): ast::Node { mut node := ast::Node{ Token: st[0], } @@ -1771,7 +1620,7 @@ impl parser { ret node } - fn appendNode(mut &self, mut &st: []&lex::Token) { + fn appendNode(mut &self, mut &st: []&token::Token) { if len(st) == 0 { ret } @@ -1781,7 +1630,7 @@ impl parser { } } - fn removeRange(self, mut i: int, id: lex::TokenId, &tokens: []&lex::Token, mut &ranges: []int) { + fn removeRange(self, mut i: int, id: token::Id, &tokens: []&token::Token, mut &ranges: []int) { close := getCloseOfBrace(id) for i >= 0; i-- { tok := tokens[ranges[i]] @@ -1793,26 +1642,26 @@ impl parser { } } - fn pushWrongOrderCloseErr(mut self, &t: &lex::Token, &tokens: []&lex::Token, &ranges: []int) { + fn pushWrongOrderCloseErr(mut self, &t: &token::Token, &tokens: []&token::Token, &ranges: []int) { match tokens[ranges[len(ranges)-1]].Id { - | lex::TokenId.LParent: + | token::Id.LParent: self.pushErr(t, build::LogMsg.ExpectedParentClose) - | lex::TokenId.LBrace: + | token::Id.LBrace: self.pushErr(t, build::LogMsg.ExpectedBraceClose) - | lex::TokenId.LBracket: + | token::Id.LBracket: self.pushErr(t, build::LogMsg.ExpectedBracketClose) } } - fn pushRangeClose(mut self, t: &lex::Token, left: lex::TokenId, &tokens: []&lex::Token, mut &ranges: []int) { + fn pushRangeClose(mut self, t: &token::Token, left: token::Id, &tokens: []&token::Token, mut &ranges: []int) { n := len(ranges) if n == 0 { match t.Id { - | lex::TokenId.RBracket: + | token::Id.RBracket: self.pushErr(t, build::LogMsg.ExtraClosedBracket) - | lex::TokenId.RBrace: + | token::Id.RBrace: self.pushErr(t, build::LogMsg.ExtraClosedBrace) - | lex::TokenId.RParent: + | token::Id.RParent: self.pushErr(t, build::LogMsg.ExtraClosedParent) } ret @@ -1822,38 +1671,38 @@ impl parser { self.removeRange(n-1, t.Id, tokens, ranges) } - fn checkRanges(mut self, &tokens: []&lex::Token) { + fn checkRanges(mut self, &tokens: []&token::Token) { let mut ranges: []int = nil for i, token in tokens { match token.Id { - | lex::TokenId.LParent - | lex::TokenId.LBrace - | lex::TokenId.LBracket: + | token::Id.LParent + | token::Id.LBrace + | token::Id.LBracket: ranges = append(ranges, i) - | lex::TokenId.RParent: - self.pushRangeClose(token, lex::TokenId.LParent, tokens, ranges) - | lex::TokenId.RBrace: - self.pushRangeClose(token, lex::TokenId.LBrace, tokens, ranges) - | lex::TokenId.RBracket: - self.pushRangeClose(token, lex::TokenId.LBracket, tokens, ranges) + | token::Id.RParent: + self.pushRangeClose(token, token::Id.LParent, tokens, ranges) + | token::Id.RBrace: + self.pushRangeClose(token, token::Id.LBrace, tokens, ranges) + | token::Id.RBracket: + self.pushRangeClose(token, token::Id.LBracket, tokens, ranges) } } for _, i in ranges { token := tokens[i] match token.Id { - | lex::TokenId.LParent: + | token::Id.LParent: self.pushErr(token, build::LogMsg.WaitCloseParent) - | lex::TokenId.LBrace: + | token::Id.LBrace: self.pushErr(token, build::LogMsg.WaitCloseBrace) - | lex::TokenId.LBracket: + | token::Id.LBracket: self.pushErr(token, build::LogMsg.WaitCloseBracket) } } } - fn parse(mut &self, mut &f: &lex::File) { + fn parse(mut &self, mut &f: &token::Fileset) { self.ast = &ast::AST{ File: f, } @@ -1875,7 +1724,7 @@ impl parser { if len(stmt.tokens) < 2 { ret } - if stmt.tokens[0].Id != lex::TokenId.Hash { + if stmt.tokens[0].Id != token::Id.Hash { break } if !build::IsTopDirective(stmt.tokens[1].Kind) { diff --git a/std/jule/parser/scope.jule b/std/jule/parser/scope.jule index 7722ec183..024a1a02c 100644 --- a/std/jule/parser/scope.jule +++ b/std/jule/parser/scope.jule @@ -2,35 +2,35 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" fn newScope(): &ast::ScopeTree { ret new(ast::ScopeTree) } // Reports whether token is statement finish point. -fn isSt(current: &lex::Token, prev: &lex::Token): (ok: bool, terminated: bool) { - ok = current.Id == lex::TokenId.Semicolon || prev.Row < current.Row - terminated = current.Id == lex::TokenId.Semicolon +fn isSt(current: &token::Token, prev: &token::Token): (ok: bool, terminated: bool) { + ok = current.Id == token::Id.Semicolon || prev.Row < current.Row + terminated = current.Id == token::Id.Semicolon ret } -fn prevIsIncompleteExpr(&tokens: []&lex::Token, &i: int): bool { +fn prevIsIncompleteExpr(&tokens: []&token::Token, &i: int): bool { // Ignore namespaces. - if i > 1 && tokens[i-2].Id == lex::TokenId.DblColon { + if i > 1 && tokens[i-2].Id == token::Id.DblColon { ret false } unsafe { prev := tokens[i-1] - ret prev.Id == lex::TokenId.Dot || - (lex::IsBinOp(prev.Id) && prev.Row < tokens[i].Row) + ret prev.Id == token::Id.Dot || + (token::IsBinOp(prev.Id) && prev.Row < tokens[i].Row) } } // Reports position of the next statement if exist, len(toks) if not. -fn nextStPos(&tokens: []&lex::Token, start: int): (int, bool) { +fn nextStPos(&tokens: []&token::Token, start: int): (int, bool) { mut braceN := 0 mut i := start for i < len(tokens); i++ { @@ -38,9 +38,9 @@ fn nextStPos(&tokens: []&lex::Token, start: int): (int, bool) { mut terminated := false tok := tokens[i] match tok.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: if braceN == 0 && i > start { if !prevIsIncompleteExpr(tokens, i) { ok, terminated = isSt(tok, tokens[i-1]) @@ -51,9 +51,9 @@ fn nextStPos(&tokens: []&lex::Token, start: int): (int, bool) { } braceN++ continue - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- if braceN == 0 && i+1 < len(tokens) { ok, terminated = isSt(tokens[i+1], tok) @@ -92,7 +92,7 @@ fn nextStPos(&tokens: []&lex::Token, start: int): (int, bool) { // Returns current statement tokens. // Starts selection at i. -fn skipSt(mut &i: int, mut tokens: []&lex::Token): ([]&lex::Token, bool) { +fn skipSt(mut &i: int, mut tokens: []&token::Token): ([]&token::Token, bool) { start := i mut terminated := false i, terminated = nextStPos(tokens, start) @@ -108,12 +108,12 @@ fn skipSt(mut &i: int, mut tokens: []&lex::Token): ([]&lex::Token, bool) { } struct stmt { - tokens: []&lex::Token + tokens: []&token::Token terminated: bool } // Splits all statements. -fn splitStmts(mut &tokens: []&lex::Token): []&stmt { +fn splitStmts(mut &tokens: []&token::Token): []&stmt { mut stmts := make([]&stmt, 0, 20) mut pos := 0 for pos < len(tokens) { @@ -150,7 +150,7 @@ impl scopeParser { ret self.pos+1 >= len(self.stmts) } - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg) { self.p.pushErr(token, fmt) } @@ -159,7 +159,7 @@ impl scopeParser { self.p.pushSuggestion(fmt, args...) } - fn insertAsNext(mut self, mut &tokens: []&lex::Token) { + fn insertAsNext(mut self, mut &tokens: []&token::Token) { self.stmts = append(self.stmts[:self.pos+1], self.stmts[self.pos:]...) self.stmts[self.pos+1] = &stmt{tokens: tokens} } @@ -169,7 +169,7 @@ impl scopeParser { ret self.stmts[self.pos] } - fn buildScope(mut self, mut &tokens: []&lex::Token, mut end: &lex::Token): &ast::ScopeTree { + fn buildScope(mut self, mut &tokens: []&token::Token, mut end: &token::Token): &ast::ScopeTree { mut s := newScope() s.Parent = self.s s.End = end @@ -180,7 +180,7 @@ impl scopeParser { ret s } - fn buildVarSt(mut self, mut &tokens: []&lex::Token): &ast::VarDecl { + fn buildVarSt(mut self, mut &tokens: []&token::Token): &ast::VarDecl { mut v := self.p.buildVar(tokens) if v != nil { v.Scope = self.s @@ -188,7 +188,7 @@ impl scopeParser { ret v } - fn buildRetSt(mut self, mut tokens: []&lex::Token): &ast::RetSt { + fn buildRetSt(mut self, mut tokens: []&token::Token): &ast::RetSt { mut st := &ast::RetSt{ Token: tokens[0], } @@ -227,7 +227,7 @@ impl scopeParser { } mut i := len(stTokens) - mut blockTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut blockTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if blockTokens == nil { self.stop() self.pushErr(it.Token, build::LogMsg.BodyNotExist) @@ -244,19 +244,19 @@ impl scopeParser { ret it } - fn buildWhileIterKind(mut self, mut &tokens: []&lex::Token): &ast::WhileKind { + fn buildWhileIterKind(mut self, mut &tokens: []&token::Token): &ast::WhileKind { ret &ast::WhileKind{ Expr: self.p.buildExpr(tokens), } } - fn getRangeKindKeysTokens(mut self, mut &toks: []&lex::Token): [][]&lex::Token { - mut vars, errs := parts(toks, lex::TokenId.Comma, true) + fn getRangeKindKeysTokens(mut self, mut &toks: []&token::Token): [][]&token::Token { + mut vars, errs := parts(toks, token::Id.Comma, true) self.p.errors = append(self.p.errors, errs...) ret vars } - fn buildRangeKindKey(mut self, mut &tokens: []&lex::Token): &ast::VarDecl { + fn buildRangeKindKey(mut self, mut &tokens: []&token::Token): &ast::VarDecl { if len(tokens) == 0 { ret nil } @@ -264,7 +264,7 @@ impl scopeParser { Token: tokens[0], Setter: tokens[0], } - if key.Token.Id == lex::TokenId.Mut { + if key.Token.Id == token::Id.Mut { key.Mutable = true if len(tokens) == 1 { self.pushErr(key.Token, build::LogMsg.InvalidSyntax) @@ -273,7 +273,7 @@ impl scopeParser { } else if len(tokens) > 1 { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) } - if key.Token.Id != lex::TokenId.Ident { + if key.Token.Id != token::Id.Ident { self.pushErr(key.Token, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret nil @@ -282,7 +282,7 @@ impl scopeParser { ret key } - fn buildRangeKindKeys(mut self, mut &parts: [][]&lex::Token): []&ast::VarDecl { + fn buildRangeKindKeys(mut self, mut &parts: [][]&token::Token): []&ast::VarDecl { let mut keys: []&ast::VarDecl = nil for (_, mut tokens) in parts { keys = append(keys, self.buildRangeKindKey(tokens)) @@ -290,7 +290,7 @@ impl scopeParser { ret keys } - fn setupRangeKindKeysPlain(mut self, mut &rng: &ast::RangeKind, mut &tokens: []&lex::Token) { + fn setupRangeKindKeysPlain(mut self, mut &rng: &ast::RangeKind, mut &tokens: []&token::Token) { mut keyTokens := self.getRangeKindKeysTokens(tokens) if len(keyTokens) == 0 { ret @@ -305,25 +305,25 @@ impl scopeParser { } } - fn setupRangeKindKeysExplicit(mut self, mut &rng: &ast::RangeKind, mut &tokens: []&lex::Token) { + fn setupRangeKindKeysExplicit(mut self, mut &rng: &ast::RangeKind, mut &tokens: []&token::Token) { mut i := 0 - mut rang := range(i, lex::TokenId.LParent, lex::TokenId.RParent, tokens) + mut rang := range(i, token::Id.LParent, token::Id.RParent, tokens) if i < len(tokens) { self.pushErr(rng.InToken, build::LogMsg.InvalidSyntax) } self.setupRangeKindKeysPlain(rng, rang) } - fn setupRangeKindKeys(mut self, mut &rng: &ast::RangeKind, mut &tokens: []&lex::Token) { - if tokens[0].Id == lex::TokenId.LParent { + fn setupRangeKindKeys(mut self, mut &rng: &ast::RangeKind, mut &tokens: []&token::Token) { + if tokens[0].Id == token::Id.LParent { self.setupRangeKindKeysExplicit(rng, tokens) ret } self.setupRangeKindKeysPlain(rng, tokens) } - fn buildRangeIterKind(mut self, mut &varTokens: []&lex::Token, - mut &exprTokens: []&lex::Token, mut &inToken: &lex::Token): &ast::RangeKind { + fn buildRangeIterKind(mut self, mut &varTokens: []&token::Token, + mut &exprTokens: []&token::Token, mut &inToken: &token::Token): &ast::RangeKind { mut rng := &ast::RangeKind{ InToken: inToken, } @@ -338,25 +338,25 @@ impl scopeParser { ret rng } - fn buildCommonIterKind(mut self, mut &tokens: []&lex::Token, &errTok: &lex::Token): ast::IterKind { + fn buildCommonIterKind(mut self, mut &tokens: []&token::Token, &errTok: &token::Token): ast::IterKind { mut braceN := 0 for (i, mut tok) in tokens { match tok.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: braceN++ continue - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- } if braceN != 0 { continue } match tok.Id { - | lex::TokenId.In: + | token::Id.In: mut declTokens := tokens[:i] mut exprTokens := tokens[i+1:] ret self.buildRangeIterKind(declTokens, exprTokens, tok) @@ -365,7 +365,7 @@ impl scopeParser { ret self.buildWhileIterKind(tokens) } - fn buildCommonIter(mut self, mut tokens: []&lex::Token): &ast::Iter { + fn buildCommonIter(mut self, mut tokens: []&token::Token): &ast::Iter { mut it := &ast::Iter{ Token: tokens[0], } @@ -381,7 +381,7 @@ impl scopeParser { it.Kind = self.buildCommonIterKind(exprTokens, it.Token) } mut i := len(exprTokens) - mut scopeTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut scopeTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if scopeTokens == nil { self.stop() self.pushErr(it.Token, build::LogMsg.BodyNotExist) @@ -402,12 +402,12 @@ impl scopeParser { ret self.buildCommonIter(st.tokens) } - fn buildBreakSt(mut self, mut &tokens: []&lex::Token): &ast::BreakSt { + fn buildBreakSt(mut self, mut &tokens: []&token::Token): &ast::BreakSt { mut brk := &ast::BreakSt{ Token: tokens[0], } if len(tokens) > 1 { - if tokens[1].Id != lex::TokenId.Ident { + if tokens[1].Id != token::Id.Ident { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedLabelIdent) } else { @@ -420,12 +420,12 @@ impl scopeParser { ret brk } - fn buildContSt(mut self, mut &tokens: []&lex::Token): &ast::ContSt { + fn buildContSt(mut self, mut &tokens: []&token::Token): &ast::ContSt { mut cont := &ast::ContSt{ Token: tokens[0], } if len(tokens) > 1 { - if tokens[1].Id != lex::TokenId.Ident { + if tokens[1].Id != token::Id.Ident { self.pushErr(tokens[1], build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedLabelIdent) } else { @@ -438,7 +438,7 @@ impl scopeParser { ret cont } - fn buildIf(mut self, mut &tokens: []&lex::Token): &ast::If { + fn buildIf(mut self, mut &tokens: []&token::Token): &ast::If { mut model := &ast::If{ Token: tokens[0], } @@ -450,7 +450,7 @@ impl scopeParser { } else { i = len(exprTokens) } - mut scopeTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut scopeTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if scopeTokens == nil { self.stop() self.pushErr(model.Token, build::LogMsg.BodyNotExist) @@ -459,7 +459,7 @@ impl scopeParser { } mut end := tokens[i-1] if i < len(tokens) { - if tokens[i].Id == lex::TokenId.Else { + if tokens[i].Id == token::Id.Else { tokens = tokens[i:] } else { self.pushErr(tokens[i], build::LogMsg.InvalidSyntax) @@ -471,13 +471,13 @@ impl scopeParser { ret model } - fn buildElse(mut self, mut &tokens: []&lex::Token): &ast::Else { + fn buildElse(mut self, mut &tokens: []&token::Token): &ast::Else { mut els := &ast::Else{ Token: tokens[0], } tokens = tokens[1:] // Remove "else" keyword. mut i := 0 - mut scopeTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut scopeTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if scopeTokens == nil { if i < len(tokens) { self.pushErr(els.Token, build::LogMsg.ElseHaveExpr) @@ -495,7 +495,7 @@ impl scopeParser { ret els } - fn buildIfElseChain(mut self, mut tokens: []&lex::Token): &ast::Conditional { + fn buildIfElseChain(mut self, mut tokens: []&token::Token): &ast::Conditional { mut chain := &ast::Conditional{ Head: self.buildIf(tokens), } @@ -503,10 +503,10 @@ impl scopeParser { ret nil } for len(tokens) != 0 { - if tokens[0].Id != lex::TokenId.Else { + if tokens[0].Id != token::Id.Else { break } - if len(tokens) > 1 && tokens[1].Id == lex::TokenId.If { + if len(tokens) > 1 && tokens[1].Id == token::Id.If { tokens = tokens[1:] // Remove else token mut elif := self.buildIf(tokens) chain.Tail = append(chain.Tail, elif) @@ -518,7 +518,7 @@ impl scopeParser { ret chain } - fn buildCoCallSt(mut self, mut tokens: []&lex::Token): &ast::Expr { + fn buildCoCallSt(mut self, mut tokens: []&token::Token): &ast::Expr { token := tokens[0] tokens = tokens[1:] // Start 1 to skip "co" token. mut e := self.p.buildExpr(tokens) @@ -534,7 +534,7 @@ impl scopeParser { ret e } - fn buildGotoSt(mut self, mut &tokens: []&lex::Token): &ast::GotoSt { + fn buildGotoSt(mut self, mut &tokens: []&token::Token): &ast::GotoSt { mut gt := &ast::GotoSt{ Token: tokens[0], } @@ -545,7 +545,7 @@ impl scopeParser { self.pushErr(tokens[2], build::LogMsg.InvalidSyntax) } mut identToken := tokens[1] - if identToken.Id != lex::TokenId.Ident { + if identToken.Id != token::Id.Ident { self.pushErr(identToken, build::LogMsg.InvalidSyntax) self.pushSuggestion(build::LogMsg.ExpectedIdentifier) ret gt @@ -554,7 +554,7 @@ impl scopeParser { ret gt } - fn buildFallSt(mut self, mut &tokens: []&lex::Token): &ast::FallSt { + fn buildFallSt(mut self, mut &tokens: []&token::Token): &ast::FallSt { mut fll := &ast::FallSt{ Token: tokens[0], } @@ -564,13 +564,13 @@ impl scopeParser { ret fll } - fn buildTypeAliasSt(mut self, mut &tokens: []&lex::Token): &ast::TypeAliasDecl { + fn buildTypeAliasSt(mut self, mut &tokens: []&token::Token): &ast::TypeAliasDecl { mut tad := self.p.buildTypeAliasDecl(tokens) tad.Scope = self.s ret tad } - fn pushCaseExpr(mut self, mut tokens: []&lex::Token, mut token: &lex::Token, + fn pushCaseExpr(mut self, mut tokens: []&token::Token, mut token: &token::Token, typeMatch: bool, mut &exprs: []&ast::Expr) { if len(tokens) == 0 { ret @@ -593,20 +593,20 @@ impl scopeParser { exprs = append(exprs, self.p.buildExpr(tokens)) } - fn buildCaseExprs(mut self, mut &tokens: []&lex::Token, mut &colon: &lex::Token, typeMatch: bool): ([]&ast::Expr, bool) { + fn buildCaseExprs(mut self, mut &tokens: []&token::Token, mut &colon: &token::Token, typeMatch: bool): ([]&ast::Expr, bool) { mut exprs := make([]&ast::Expr, 0, 1) mut braceN := 0 mut j := 0 for (i, mut tok) in tokens { match tok.Id { - | lex::TokenId.LParent - | lex::TokenId.LBrace - | lex::TokenId.LBracket: + | token::Id.LParent + | token::Id.LBrace + | token::Id.LBracket: braceN++ continue - | lex::TokenId.RParent - | lex::TokenId.RBrace - | lex::TokenId.RBracket: + | token::Id.RParent + | token::Id.RBrace + | token::Id.RBracket: braceN-- continue } @@ -615,7 +615,7 @@ impl scopeParser { continue } match { - | tok.Id == lex::TokenId.Vline: + | tok.Id == token::Id.Vline: exprTokens := tokens[j:i] if len(exprTokens) == 0 { self.pushErr(tok, build::LogMsg.MissingExpr) @@ -623,7 +623,7 @@ impl scopeParser { self.pushCaseExpr(tokens[j:i], tok, typeMatch, exprs) } j = i + 1 - | tok.Id == lex::TokenId.Colon: + | tok.Id == token::Id.Colon: colon = tok self.pushCaseExpr(tokens[j:i], tok, typeMatch, exprs) tokens = tokens[i+1:] @@ -635,7 +635,7 @@ impl scopeParser { ret nil, false } - fn buildCaseScope(mut self, mut &tokens: []&lex::Token): &ast::ScopeTree { + fn buildCaseScope(mut self, mut &tokens: []&token::Token): &ast::ScopeTree { mut n := 0 for { mut i := 0 @@ -644,7 +644,7 @@ impl scopeParser { break } tok := next[0] - if tok.Id != lex::TokenId.Vline { + if tok.Id != token::Id.Vline { n += i continue } @@ -653,7 +653,7 @@ impl scopeParser { tokens = tokens[n:] ret scope } - let mut end: &lex::Token + let mut end: &token::Token if len(tokens) > 0 { end = tokens[len(tokens)-1] } @@ -662,12 +662,12 @@ impl scopeParser { ret scope } - fn buildCase(mut self, mut &tokens: []&lex::Token, typeMatch: bool): (&ast::Case, bool) { + fn buildCase(mut self, mut &tokens: []&token::Token, typeMatch: bool): (&ast::Case, bool) { mut c := &ast::Case{ Token: tokens[0], } tokens = tokens[1:] // Remove case prefix. - let mut colon: &lex::Token = nil + let mut colon: &token::Token = nil if len(tokens) == 0 { self.pushErr(c.Token, build::LogMsg.InvalidSyntax) ret nil, false @@ -681,13 +681,13 @@ impl scopeParser { ret c, isDefault } - fn buildCases(mut self, mut tokens: []&lex::Token, typeMatch: bool): ([]&ast::Case, &ast::Else) { + fn buildCases(mut self, mut tokens: []&token::Token, typeMatch: bool): ([]&ast::Case, &ast::Else) { let mut cases: []&ast::Case = nil let mut def: &ast::Else = nil mut defNotLast := false for len(tokens) > 0 { mut tok := tokens[0] - if tok.Id != lex::TokenId.Vline { + if tok.Id != token::Id.Vline { self.pushErr(tok, build::LogMsg.InvalidSyntax) break } @@ -715,13 +715,13 @@ impl scopeParser { ret cases, def } - fn buildMatchCase(mut self, mut tokens: []&lex::Token): &ast::MatchCase { + fn buildMatchCase(mut self, mut tokens: []&token::Token): &ast::MatchCase { mut m := &ast::MatchCase{ Token: tokens[0], } tokens = tokens[1:] // Remove "match" keyword. - if len(tokens) > 0 && tokens[0].Id == lex::TokenId.Type { + if len(tokens) > 0 && tokens[0].Id == token::Id.Type { m.TypeMatch = true tokens = tokens[1:] // Skip "type" keyword } @@ -734,7 +734,7 @@ impl scopeParser { } mut i := len(exprTokens) - mut blockToks := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut blockToks := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if blockToks == nil { self.stop() self.pushErr(m.Token, build::LogMsg.BodyNotExist) @@ -748,11 +748,11 @@ impl scopeParser { ret m } - fn buildScopeSt(mut self, mut tokens: []&lex::Token): &ast::ScopeTree { + fn buildScopeSt(mut self, mut tokens: []&token::Token): &ast::ScopeTree { mut isUnsafe := false mut isDeferred := false mut token := tokens[0] - if token.Id == lex::TokenId.Unsafe { + if token.Id == token::Id.Unsafe { isUnsafe = true tokens = tokens[1:] if len(tokens) == 0 { @@ -760,7 +760,7 @@ impl scopeParser { ret nil } token = tokens[0] - if token.Id == lex::TokenId.Defer { + if token.Id == token::Id.Defer { isDeferred = true tokens = tokens[1:] if len(tokens) == 0 { @@ -768,7 +768,7 @@ impl scopeParser { ret nil } } - } else if token.Id == lex::TokenId.Defer { + } else if token.Id == token::Id.Defer { isDeferred = true tokens = tokens[1:] if len(tokens) == 0 { @@ -778,7 +778,7 @@ impl scopeParser { } mut i := 0 - mut scopeTokens := range(i, lex::TokenId.LBrace, lex::TokenId.RBrace, tokens) + mut scopeTokens := range(i, token::Id.LBrace, token::Id.RBrace, tokens) if scopeTokens == nil { self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil @@ -791,7 +791,7 @@ impl scopeParser { ret scope } - fn buildLabelSt(mut self, mut &tokens: []&lex::Token): &ast::LabelSt { + fn buildLabelSt(mut self, mut &tokens: []&token::Token): &ast::LabelSt { mut lbl := &ast::LabelSt{ Token: tokens[0], Ident: tokens[0].Kind, @@ -806,40 +806,40 @@ impl scopeParser { ret lbl } - fn buildIdSt(mut self, mut &tokens: []&lex::Token): (ast::StmtData, ok: bool) { + fn buildIdSt(mut self, mut &tokens: []&token::Token): (ast::StmtData, ok: bool) { if len(tokens) == 1 { ret } mut token := tokens[1] match token.Id { - | lex::TokenId.Colon: + | token::Id.Colon: ret self.buildLabelSt(tokens), true } ret } - fn buildAssignInfo(mut self, mut &tokens: []&lex::Token): &assignInfo { + fn buildAssignInfo(mut self, mut &tokens: []&token::Token): &assignInfo { mut info := &assignInfo{ ok: true, } mut braceN := 0 for (i, mut token) in tokens { match token.Id { - | lex::TokenId.LBrace - | lex::TokenId.LBracket - | lex::TokenId.LParent: + | token::Id.LBrace + | token::Id.LBracket + | token::Id.LParent: braceN++ - | lex::TokenId.RBrace - | lex::TokenId.RBracket - | lex::TokenId.RParent: + | token::Id.RBrace + | token::Id.RBracket + | token::Id.RParent: braceN-- } match { | braceN > 0: continue - | !lex::IsAssignOp(token.Id) && token.Id != lex::TokenId.ColonEq: + | !token::IsAssignOp(token.Id) && token.Id != token::Id.ColonEq: continue } @@ -850,11 +850,11 @@ impl scopeParser { info.setter = token if i+1 >= len(tokens) { info.r = nil - info.ok = lex::IsPostfixOp(info.setter.Id) + info.ok = token::IsPostfixOp(info.setter.Id) break } info.r = tokens[i+1:] - if lex::IsPostfixOp(info.setter.Id) { + if token::IsPostfixOp(info.setter.Id) { if len(info.r) > 0 { self.pushErr(info.r[0], build::LogMsg.InvalidSyntax) info.r = nil @@ -865,18 +865,18 @@ impl scopeParser { ret info } - fn buildAssignL(mut self, mut &tokens: []&lex::Token): &ast::AssignLeft { + fn buildAssignL(mut self, mut &tokens: []&token::Token): &ast::AssignLeft { mut l := &ast::AssignLeft{ Token: tokens[0], } - if tokens[0].Id == lex::TokenId.Ident { + if tokens[0].Id == token::Id.Ident { l.Ident = l.Token.Kind } l.Expr = self.p.buildExpr(tokens) ret l } - fn buildAssignLs(mut self, mut &parts: [][]&lex::Token): []&ast::AssignLeft { + fn buildAssignLs(mut self, mut &parts: [][]&token::Token): []&ast::AssignLeft { let mut lefts: []&ast::AssignLeft = nil for (_, mut part) in parts { mut l := self.buildAssignL(part) @@ -885,7 +885,7 @@ impl scopeParser { ret lefts } - fn buildPlainAssign(mut self, mut &tokens: []&lex::Token): (ast::StmtData, bool) { + fn buildPlainAssign(mut self, mut &tokens: []&token::Token): (ast::StmtData, bool) { mut info := self.buildAssignInfo(tokens) if !info.ok { ret nil, false @@ -896,7 +896,7 @@ impl scopeParser { } // Caught declaration assignments. - if info.setter.Id == lex::TokenId.ColonEq { + if info.setter.Id == token::Id.ColonEq { assign.Declarative = true assign.Right = self.p.buildExpr(info.r) ok := self.buildDeclAssign1(info.l, assign) @@ -925,7 +925,7 @@ impl scopeParser { ret assign, true } - mut parts, errs := parts(info.l, lex::TokenId.Comma, true) + mut parts, errs := parts(info.l, token::Id.Comma, true) if len(errs) > 0 { self.p.errors = append(self.p.errors, errs...) ret nil, false @@ -939,9 +939,9 @@ impl scopeParser { ret assign, true } - fn buildDeclAssign1(mut self, mut &lefts: []&lex::Token, mut &assign: &ast::AssignSt): bool { + fn buildDeclAssign1(mut self, mut &lefts: []&token::Token, mut &assign: &ast::AssignSt): bool { // Lefts - mut parts, errs := parts(lefts, lex::TokenId.Comma, true) + mut parts, errs := parts(lefts, token::Id.Comma, true) if len(errs) > 0 { self.p.errors = append(self.p.errors, errs...) ret false @@ -952,7 +952,7 @@ impl scopeParser { mut isRef := false token := part[0] - if token.Id == lex::TokenId.Mut { + if token.Id == token::Id.Mut { isMut = true part = part[1:] if len(part) == 0 { @@ -961,7 +961,7 @@ impl scopeParser { } } - if part[0].Id == lex::TokenId.Amper { + if part[0].Id == token::Id.Amper { isRef = true part = part[1:] if len(part) == 0 { @@ -970,7 +970,7 @@ impl scopeParser { } } - if part[0].Id != lex::TokenId.Ident && part[0].Id != lex::TokenId.LParent { + if part[0].Id != token::Id.Ident && part[0].Id != token::Id.LParent { self.pushErr(token, build::LogMsg.InvalidSyntax) ret false } @@ -987,14 +987,14 @@ impl scopeParser { ret true } - fn buildDeclAssign(mut self, mut tokens: []&lex::Token): (&ast::AssignSt, bool) { + fn buildDeclAssign(mut self, mut tokens: []&token::Token): (&ast::AssignSt, bool) { if len(tokens) < 1 { ret nil, false } tokens = tokens[1:] // Skip "let" keyword mut token := tokens[0] - if token.Id != lex::TokenId.LParent { + if token.Id != token::Id.LParent { ret nil, false } @@ -1003,13 +1003,13 @@ impl scopeParser { } mut i := 0 - mut rang := range(i, lex::TokenId.LParent, lex::TokenId.RParent, tokens) + mut rang := range(i, token::Id.LParent, token::Id.RParent, tokens) if rang == nil { self.pushErr(token, build::LogMsg.InvalidSyntax) ret nil, false } else if i+1 < len(tokens) { assign.Setter = tokens[i] - if assign.Setter.Id != lex::TokenId.Eq { + if assign.Setter.Id != token::Id.Eq { self.pushErr(assign.Setter, build::LogMsg.InvalidSyntax) } i++ @@ -1021,12 +1021,12 @@ impl scopeParser { ret assign, ok } - fn buildAssignSt(mut self, mut &tokens: []&lex::Token): (st: ast::StmtData, ok: bool) { + fn buildAssignSt(mut self, mut &tokens: []&token::Token): (st: ast::StmtData, ok: bool) { if !checkAssignTokens(tokens) { ret nil, false } match tokens[0].Id { - | lex::TokenId.Let: + | token::Id.Let: st, ok = self.buildDeclAssign(tokens) |: st, ok = self.buildPlainAssign(tokens) @@ -1034,7 +1034,7 @@ impl scopeParser { ret } - fn buildUseExpr(mut self, mut &tokens: []&lex::Token): &ast::UseExpr { + fn buildUseExpr(mut self, mut &tokens: []&token::Token): &ast::UseExpr { if len(tokens) == 1 { self.pushErr(tokens[0], build::LogMsg.MissingExpr) ret nil @@ -1053,14 +1053,14 @@ impl scopeParser { ret nil } match st.tokens[1].Id { - | lex::TokenId.For: + | token::Id.For: st.tokens = st.tokens[1:] mut iter := self.buildIterSt(st) if iter != nil { iter.Comptime = true } ret iter - | lex::TokenId.Match: + | token::Id.Match: st.tokens = st.tokens[1:] mut mt := self.buildMatchCase(st.tokens) if mt != nil { @@ -1074,7 +1074,7 @@ impl scopeParser { fn buildSt(mut self, mut &st: &stmt): ast::StmtData { mut token := st.tokens[0] - if token.Id == lex::TokenId.Ident { + if token.Id == token::Id.Ident { mut s, ok := self.buildIdSt(st.tokens) if ok { ret s @@ -1087,45 +1087,45 @@ impl scopeParser { } match token.Id { - | lex::TokenId.Use: + | token::Id.Use: ret self.buildUseExpr(st.tokens) - | lex::TokenId.Const: + | token::Id.Const: ret self.buildConstSt(st) - | lex::TokenId.Static - | lex::TokenId.Let - | lex::TokenId.Mut: + | token::Id.Static + | token::Id.Let + | token::Id.Mut: ret self.buildVarSt(st.tokens) - | lex::TokenId.Ret: + | token::Id.Ret: ret self.buildRetSt(st.tokens) - | lex::TokenId.For: + | token::Id.For: ret self.buildIterSt(st) - | lex::TokenId.Break: + | token::Id.Break: ret self.buildBreakSt(st.tokens) - | lex::TokenId.Cont: + | token::Id.Cont: ret self.buildContSt(st.tokens) - | lex::TokenId.If: + | token::Id.If: ret self.buildIfElseChain(st.tokens) - | lex::TokenId.Co: + | token::Id.Co: ret self.buildCoCallSt(st.tokens) - | lex::TokenId.Goto: + | token::Id.Goto: ret self.buildGotoSt(st.tokens) - | lex::TokenId.Fall: + | token::Id.Fall: ret self.buildFallSt(st.tokens) - | lex::TokenId.Type: + | token::Id.Type: ret self.buildTypeAliasSt(st.tokens) - | lex::TokenId.Match: + | token::Id.Match: ret self.buildMatchCase(st.tokens) - | lex::TokenId.Unsafe: + | token::Id.Unsafe: if len(st.tokens) < 1 { break } - if st.tokens[1].Id == lex::TokenId.Defer || - st.tokens[1].Id == lex::TokenId.LBrace { // Scope. + if st.tokens[1].Id == token::Id.Defer || + st.tokens[1].Id == token::Id.LBrace { // Scope. ret self.buildScopeSt(st.tokens) } - | lex::TokenId.Defer: + | token::Id.Defer: ret self.buildScopeSt(st.tokens) - | lex::TokenId.LBrace: + | token::Id.LBrace: ret self.buildScopeSt(st.tokens) } mut expr := self.p.buildExpr(st.tokens) @@ -1136,7 +1136,7 @@ impl scopeParser { ret nil } - fn build(mut self, mut &tokens: []&lex::Token, mut &s: &ast::ScopeTree) { + fn build(mut self, mut &tokens: []&token::Token, mut &s: &ast::ScopeTree) { if s == nil { ret } diff --git a/std/jule/parser/type.jule b/std/jule/parser/type.jule index 846239f80..60385581e 100644 --- a/std/jule/parser/type.jule +++ b/std/jule/parser/type.jule @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" fn buildVoidType(): &ast::TypeDecl { ret new(ast::TypeDecl) } -fn buildPrimType(mut t: &lex::Token): &ast::TypeDecl { +fn buildPrimType(mut t: &token::Token): &ast::TypeDecl { ret &ast::TypeDecl{ Token: t, Kind: &ast::IdentTypeDecl{ @@ -22,13 +22,13 @@ fn buildPrimType(mut t: &lex::Token): &ast::TypeDecl { struct typeBuilder { p: &parser - tokens: []&lex::Token + tokens: []&token::Token i: *int err: bool } impl typeBuilder { - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg) { if self.err { self.p.pushErr(token, fmt) } @@ -45,29 +45,31 @@ impl typeBuilder { mut t := &ast::TypeDecl{ Token: self.tokens[*self.i], } - - mut nst := new(ast::NamespaceTypeDecl) - mut n := 0 - for *self.i < len(self.tokens); *self.i++ { - mut token := self.tokens[*self.i] - if n%2 == 0 { - if token.Id != lex::TokenId.Ident { - self.pushErr(token, build::LogMsg.InvalidSyntax) - self.pushSuggestion(build::LogMsg.ExpectedIdentifier) - } - nst.Idents = append(nst.Idents, token) - } else if token.Id != lex::TokenId.DblColon { - break - } - n++ + mut ns := new(ast::NamespaceTypeDecl) + ns.Namespace = self.tokens[*self.i] + if ns.Namespace.Id != token::Id.Ident && ns.Namespace.Id != token::Id.Unsafe { + self.pushErr(ns.Namespace, build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedIdentifier) } - - // Remove selected identifier token. - nst.Idents = nst.Idents[:len(nst.Idents)-1] - - *self.i-- // Set offset to last identifier. - nst.Kind = self.buildIdent() - t.Kind = nst + *self.i++ + if len(self.tokens) <= *self.i { + self.pushErr(ns.Namespace, build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedDblColon) + ret nil + } + if self.tokens[*self.i].Id != token::Id.DblColon { + self.pushErr(self.tokens[*self.i], build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedDblColon) + ret nil + } + *self.i++ + if len(self.tokens) <= *self.i { + self.pushErr(self.tokens[*self.i-1], build::LogMsg.InvalidSyntax) + self.pushSuggestion(build::LogMsg.ExpectedIdentifier) + ret nil + } + ns.Kind = self.buildIdent() + t.Kind = ns ret t } @@ -76,7 +78,7 @@ impl typeBuilder { ret nil } token := self.tokens[*self.i] - if token.Id != lex::TokenId.LBracket { + if token.Id != token::Id.LBracket { ret nil } @@ -98,15 +100,15 @@ impl typeBuilder { ret types } - unsafe fn identGenerics(mut self): [][]&lex::Token { + unsafe fn identGenerics(mut self): [][]&token::Token { first := *self.i mut rangeN := 0 for *self.i < len(self.tokens); *self.i++ { token := self.tokens[*self.i] match token.Id { - | lex::TokenId.LBracket: + | token::Id.LBracket: rangeN++ - | lex::TokenId.RBracket: + | token::Id.RBracket: rangeN-- } if rangeN == 0 { @@ -115,7 +117,7 @@ impl typeBuilder { } } mut tokens := self.tokens[first+1 : *self.i-1] // Take range of brackets. - mut parts, errors := parts(tokens, lex::TokenId.Comma, true) + mut parts, errors := parts(tokens, token::Id.Comma, true) if self.err { self.p.errors = append(self.p.errors, errors...) } @@ -124,7 +126,7 @@ impl typeBuilder { unsafe fn buildIdent(mut self): &ast::TypeDecl { mut next := *self.i+1 < len(self.tokens) - if next && self.tokens[*self.i+1].Id == lex::TokenId.DblColon { + if next && self.tokens[*self.i+1].Id == token::Id.DblColon { ret self.buildNamespace() } mut token := self.tokens[*self.i] @@ -138,7 +140,7 @@ impl typeBuilder { Token: token, Kind: it, } - if !next || self.tokens[*self.i].Id != lex::TokenId.Dot { + if !next || self.tokens[*self.i].Id != token::Id.Dot { it.Generics = self.buildGenerics() ret itd } @@ -147,7 +149,7 @@ impl typeBuilder { ret itd } *self.i++ - if self.tokens[*self.i].Id != lex::TokenId.Ident { + if self.tokens[*self.i].Id != token::Id.Ident { self.pushErr(self.tokens[*self.i-1], build::LogMsg.InvalidSyntax) ret itd } @@ -167,7 +169,7 @@ impl typeBuilder { } unsafe fn buildCppLink(mut self): &ast::TypeDecl { - if *self.i+1 >= len(self.tokens) || self.tokens[*self.i+1].Id != lex::TokenId.Dot { + if *self.i+1 >= len(self.tokens) || self.tokens[*self.i+1].Id != token::Id.Dot { self.pushErr(self.tokens[*self.i], build::LogMsg.InvalidSyntax) ret nil } @@ -200,7 +202,7 @@ impl typeBuilder { } *self.i++ - if self.tokens[*self.i].Id == lex::TokenId.Unsafe { + if self.tokens[*self.i].Id == token::Id.Unsafe { *self.i++ ret &ast::TypeDecl{ Token: token, @@ -260,7 +262,7 @@ impl typeBuilder { } unsafe fn buildArr(mut self): &ast::TypeDecl { - mut exprTokens := range(*self.i, lex::TokenId.LBracket, lex::TokenId.RBracket, self.tokens) + mut exprTokens := range(*self.i, token::Id.LBracket, token::Id.RBracket, self.tokens) if *self.i >= len(self.tokens) { self.pushErr(self.tokens[*self.i-1], build::LogMsg.MissingType) ret nil @@ -276,7 +278,7 @@ impl typeBuilder { } mut token := exprTokens[0] - if len(exprTokens) == 1 && token.Id == lex::TokenId.TripleDot { + if len(exprTokens) == 1 && token.Id == token::Id.TripleDot { // Ignore. } else { arrt.Size = self.p.buildExpr(exprTokens) @@ -297,7 +299,7 @@ impl typeBuilder { } // Get key type tokens without brackets. - mut keyTokens := range(*self.i, lex::TokenId.LBracket, lex::TokenId.RBracket, self.tokens) + mut keyTokens := range(*self.i, token::Id.LBracket, token::Id.RBracket, self.tokens) if *self.i >= len(self.tokens) { self.pushErr(self.tokens[*self.i-1], build::LogMsg.MissingType) ret nil @@ -335,7 +337,7 @@ impl typeBuilder { } *self.i++ token = self.tokens[*self.i] - if token.Id == lex::TokenId.RBracket { + if token.Id == token::Id.RBracket { ret self.buildSlc() } *self.i-- // Point to left bracket. @@ -345,12 +347,12 @@ impl typeBuilder { unsafe fn step(mut self): &ast::TypeDecl { token := self.tokens[*self.i] match token.Id { - | lex::TokenId.Ident: + | token::Id.Ident: ret self.buildIdent() - | lex::TokenId.Cpp: + | token::Id.Cpp: ret self.buildCppLink() - | lex::TokenId.Unsafe: - if len(self.tokens)-*self.i > 1 && self.tokens[*self.i+1].Id == lex::TokenId.Fn { + | token::Id.Unsafe: + if len(self.tokens)-*self.i > 1 && self.tokens[*self.i+1].Id == token::Id.Fn { // unsafe function *self.i++ // point to function keyword mut f := self.buildFn() @@ -359,21 +361,21 @@ impl typeBuilder { } ret f } - | lex::TokenId.Fn: + | token::Id.Fn: ret self.buildFn() - | lex::TokenId.Star: + | token::Id.Star: ret self.buildPtr() - | lex::TokenId.Amper: + | token::Id.Amper: ret self.buildSptr() - | lex::TokenId.DblAmper: + | token::Id.DblAmper: ret &ast::TypeDecl{ Kind: &ast::SptrTypeDecl{ Elem: self.buildSptr(), }, } - | lex::TokenId.LBracket: + | token::Id.LBracket: ret self.buildEnumerable() - | lex::TokenId.Map: + | token::Id.Map: ret self.buildMap() } *self.i++ diff --git a/std/jule/sema/analysis.jule b/std/jule/sema/analysis.jule index 68d26a302..a21b9fd50 100644 --- a/std/jule/sema/analysis.jule +++ b/std/jule/sema/analysis.jule @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use ast for std::jule::ast -use build for std::jule::build +use "std/jule/ast" +use "std/jule/build" +use "std/unsafe" // Flags for semantic analysis. -enum SemaFlag { +enum Flag { Default: 0, // Default semantic analysis of Jule. Shadowing: 1 << 0, // Default + enable shadowing. } @@ -34,15 +34,15 @@ fn collectImplicitImports(mut &s: &sema, mut &file: &SymTab) { break } match imp.LinkPath { - | "std::runtime": + | "std/runtime": s.meta.runtime = imp |: - panic("implementation mistake in implicit import collection, this panic call should be unreachable") + panic("sema: implementation mistake in implicit import collection, this panic call should be unreachable") } } } -fn analyzePackage(mut &files: []&ast::AST, mut &importer: Importer, &flags: SemaFlag): (&Package, []build::Log) { +fn analyzePackage(mut &files: []&ast::AST, mut &importer: Importer, &flags: Flag): (&Package, []build::Log) { // Build symbol tables of files. mut tables := make([]&SymTab, 0, len(files)) for (_, mut f) in files { @@ -92,7 +92,7 @@ fn analyzePackage(mut &files: []&ast::AST, mut &importer: Importer, &flags: Sema // Risks: // - You can pass nil to importer, but panics if importer is nil and // semantic analyzer used nil importer. -fn AnalyzePackage(mut files: []&ast::AST, mut importer: Importer, flags: SemaFlag): (&Package, []build::Log) { +fn AnalyzePackage(mut files: []&ast::AST, mut importer: Importer, flags: Flag): (&Package, []build::Log) { if len(files) == 0 { ret nil, nil } @@ -116,7 +116,7 @@ fn AnalyzePackage(mut files: []&ast::AST, mut importer: Importer, flags: SemaFla // Risks: // - You can pass nil to importer, but panics if importer is nil and // semantic analyzer used nil importer. -fn AnalyzeFile(mut f: &ast::AST, mut importer: Importer, flags: SemaFlag): (&SymTab, []build::Log) { +fn AnalyzeFile(mut f: &ast::AST, mut importer: Importer, flags: Flag): (&SymTab, []build::Log) { let mut files: [1]&ast::AST = [f] mut _files := unsafe::Slice(&files[0], len(files), len(files)) mut pkg, mut errors := AnalyzePackage(_files, importer, flags) diff --git a/std/jule/sema/builtin.jule b/std/jule/sema/builtin.jule index bc7ae114d..5b1383e44 100644 --- a/std/jule/sema/builtin.jule +++ b/std/jule/sema/builtin.jule @@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use fmt for std::fmt -use ast for std::jule::ast -use mod for std::jule::internal::mod -use build for std::jule::build -use constant for std::jule::constant +use "std/fmt" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/internal/mod" +use "std/jule/types" // Type alias for built-in function callers. // @@ -64,22 +65,22 @@ fn primTypeAlias(mut &k: &TypeKind): &TypeAlias { static mut primNil = &TypeKind{Kind: nil} static mut primVoid = &TypeKind{Kind: buildPrimType("void")} -static mut primAny = &TypeKind{Kind: buildPrimType(PrimKind.Any)} -static mut primStr = &TypeKind{Kind: buildPrimType(PrimKind.Str)} -static mut primBool = &TypeKind{Kind: buildPrimType(PrimKind.Bool)} -static mut primUintptr = &TypeKind{Kind: buildPrimType(PrimKind.Uintptr)} -static mut primUint = &TypeKind{Kind: buildPrimType(PrimKind.Uint)} -static mut primInt = &TypeKind{Kind: buildPrimType(PrimKind.Int)} -static mut primI8 = &TypeKind{Kind: buildPrimType(PrimKind.I8)} -static mut primI16 = &TypeKind{Kind: buildPrimType(PrimKind.I16)} -static mut primI32 = &TypeKind{Kind: buildPrimType(PrimKind.I32)} -static mut primI64 = &TypeKind{Kind: buildPrimType(PrimKind.I64)} -static mut primU8 = &TypeKind{Kind: buildPrimType(PrimKind.U8)} -static mut primU16 = &TypeKind{Kind: buildPrimType(PrimKind.U16)} -static mut primU32 = &TypeKind{Kind: buildPrimType(PrimKind.U32)} -static mut primU64 = &TypeKind{Kind: buildPrimType(PrimKind.U64)} -static mut primF32 = &TypeKind{Kind: buildPrimType(PrimKind.F32)} -static mut primF64 = &TypeKind{Kind: buildPrimType(PrimKind.F64)} +static mut primAny = &TypeKind{Kind: buildPrimType(types::Kind.Any)} +static mut primStr = &TypeKind{Kind: buildPrimType(types::Kind.Str)} +static mut primBool = &TypeKind{Kind: buildPrimType(types::Kind.Bool)} +static mut primUintptr = &TypeKind{Kind: buildPrimType(types::Kind.Uintptr)} +static mut primUint = &TypeKind{Kind: buildPrimType(types::Kind.Uint)} +static mut primInt = &TypeKind{Kind: buildPrimType(types::Kind.Int)} +static mut primI8 = &TypeKind{Kind: buildPrimType(types::Kind.I8)} +static mut primI16 = &TypeKind{Kind: buildPrimType(types::Kind.I16)} +static mut primI32 = &TypeKind{Kind: buildPrimType(types::Kind.I32)} +static mut primI64 = &TypeKind{Kind: buildPrimType(types::Kind.I64)} +static mut primU8 = &TypeKind{Kind: buildPrimType(types::Kind.U8)} +static mut primU16 = &TypeKind{Kind: buildPrimType(types::Kind.U16)} +static mut primU32 = &TypeKind{Kind: buildPrimType(types::Kind.U32)} +static mut primU64 = &TypeKind{Kind: buildPrimType(types::Kind.U64)} +static mut primF32 = &TypeKind{Kind: buildPrimType(types::Kind.F32)} +static mut primF64 = &TypeKind{Kind: buildPrimType(types::Kind.F64)} fn findBuiltinVar(&ident: str): &Var { match ident { @@ -271,13 +272,13 @@ fn findBuiltinDefStdJuleIntegrated(&ident: str): any { fn findPackageBuiltinDef(&linkPath: str, &ident: str): any { match linkPath { - | "std::comptime": + | "std/comptime": ret findBuiltinDefStdComptime(ident) - | "std::debug": + | "std/debug": ret findBuiltinDefStdDebug(ident) - | "std::mem": + | "std/mem": ret findBuiltinDefStdMem(ident) - | "std::jule::integrated": + | "std/jule/integrated": ret findBuiltinDefStdJuleIntegrated(ident) |: ret nil @@ -1081,7 +1082,7 @@ fn builtinCallerStdJuleIntegratedEmit(mut &e: &eval, mut &fc: &ast::FnCallExpr, } if argd.Kind.Prim() == nil || !argd.Kind.Prim().IsStr() { - e.pushErr(fc.Args[0].Token, build::LogMsg.IncompatibleTypes, PrimKind.Str, argd.Kind.Str()) + e.pushErr(fc.Args[0].Token, build::LogMsg.IncompatibleTypes, types::Kind.Str, argd.Kind.Str()) ret nil } diff --git a/std/jule/sema/comptime.jule b/std/jule/sema/comptime.jule index 032a6bd7f..149c51b80 100644 --- a/std/jule/sema/comptime.jule +++ b/std/jule/sema/comptime.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex -use constant for std::jule::constant -use types for std::jule::types +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/token" +use "std/jule/types" // All comptime-structure methods starts with underscore (_). @@ -97,7 +97,7 @@ impl comptimeRangeKind for comptimeStructFields { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -210,7 +210,7 @@ impl comptimeRangeKind for comptimeStatics { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -308,7 +308,7 @@ impl comptimeRangeKind for comptimeEnumFields { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -441,7 +441,7 @@ impl comptimeRangeKind for comptimeParams { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -501,7 +501,7 @@ impl comptimeRangeKind for comptimeTypeInfos { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -675,10 +675,10 @@ impl comptimeTypeInfo { | prim.IsUintptr(): item = enm.FindItem("Uintptr") |: - panic("Kind(): unimplemented type for std::comptime: " + self.base.Str()) + panic("sema: Kind(): unimplemented type for std::comptime: " + self.base.Str()) } |: - panic("Kind(): unimplemented type for std::comptime: " + self.base.Str()) + panic("sema: Kind(): unimplemented type for std::comptime: " + self.base.Str()) } ret evalEnumStatic(e.s, enm, item, fc.Token, e.getOwnerRefers()) } @@ -693,7 +693,7 @@ impl comptimeTypeInfo { e.pushErr(fc.Token, build::LogMsg.InvalidTypeForFn, self.base.Str(), "Bits") ret nil } - n := types::BitsizeOf(prim.Kind) + n := types::BitSizeOf(prim.Kind) if n == -1 { e.pushErr(fc.Token, build::LogMsg.InvalidTypeForFn, self.base.Str(), "Bits") ret nil @@ -1195,7 +1195,7 @@ impl comptimeValue { } prim := d.Kind.Prim() if prim == nil || !prim.IsStr() { - e.pushErr(arg.Token, build::LogMsg.IncompatibleTypes, PrimKind.Str, d.Kind.Str()) + e.pushErr(arg.Token, build::LogMsg.IncompatibleTypes, types::Kind.Str, d.Kind.Str()) ret nil } ident := d.Constant.ReadStr() @@ -1237,7 +1237,7 @@ impl comptimeValue { } prim := d.Kind.Prim() if prim == nil || !prim.IsStr() { - e.pushErr(arg.Token, build::LogMsg.IncompatibleTypes, PrimKind.Str, d.Kind.Str()) + e.pushErr(arg.Token, build::LogMsg.IncompatibleTypes, types::Kind.Str, d.Kind.Str()) ret nil } ident := d.Constant.ReadStr() @@ -1329,7 +1329,7 @@ impl comptimeRangeKind for comptimeFiles { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -1468,7 +1468,7 @@ impl comptimeRangeKind for comptimeDecls { keyA.Value = &Value{ Data: new(Data), } - keyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + keyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } if keyB != nil { keyB.Constant = true @@ -2037,7 +2037,7 @@ fn buildAsComptimeMethodData(mut &f: &FnIns): &Data { fn findComptimePackage(mut &s: &sema): &ImportInfo { ret s.SelectPackage(fn(pkg: &ImportInfo): bool { - ret pkg.LinkPath == "std::comptime" + ret pkg.LinkPath == "std/comptime" }) } diff --git a/std/jule/sema/constrait.jule b/std/jule/sema/constrait.jule index 9fbb8b4b8..4ff701a88 100644 --- a/std/jule/sema/constrait.jule +++ b/std/jule/sema/constrait.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex -use types for std::jule::types -use strings for std::strings +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" +use "std/jule/types" +use "std/strings" enum builtinConstraint: str { Signed: "signed", @@ -53,7 +53,7 @@ struct constraintChecker { mut si: &StructIns // Error that will use as error token. - mut et: &lex::Token + mut et: &token::Token // Whether instance is unique. mut uniq: bool @@ -141,7 +141,7 @@ impl constraintChecker { } fn toStrConstraints(g: &InsGeneric): str { - mut sb := strings::StrBuilder.New(1 << 7) + mut sb := strings::Builder.New(1 << 7) for i, c in g.Constraint { sb.WriteStr(c.Str()) if len(g.Constraint)-i > 1 { diff --git a/std/jule/sema/directive.jule b/std/jule/sema/directive.jule index f9bf36041..19f50b5da 100644 --- a/std/jule/sema/directive.jule +++ b/std/jule/sema/directive.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" struct directiveChecker { s: &sema @@ -71,7 +71,7 @@ impl directiveChecker { } arg := d.Args[0] - if arg.Id != lex::TokenId.Lit { + if arg.Id != token::Id.Lit { self.s.pushErr(arg, build::LogMsg.InvalidSyntax) ret } @@ -124,7 +124,7 @@ impl directiveChecker { } arg := d.Args[0] - if arg.Id != lex::TokenId.Lit { + if arg.Id != token::Id.Lit { self.s.pushErr(arg, build::LogMsg.InvalidSyntax) ret } @@ -185,7 +185,7 @@ impl directiveChecker { ret } arg := d.Args[0] - if arg.Id != lex::TokenId.Lit { + if arg.Id != token::Id.Lit { self.s.pushErr(arg, build::LogMsg.InvalidSyntax) ret } diff --git a/std/jule/sema/enum.jule b/std/jule/sema/enum.jule index 3451ae707..e477db5b7 100644 --- a/std/jule/sema/enum.jule +++ b/std/jule/sema/enum.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex +use "std/jule/token" // Enum item. struct EnumItem { - Token: &lex::Token + Token: &token::Token Ident: str Value: &Value } @@ -20,7 +20,7 @@ impl EnumItem { // Enum. struct Enum { - Token: &lex::Token + Token: &token::Token Public: bool Ident: str Kind: &TypeSymbol @@ -56,14 +56,14 @@ impl Enum { // TypeEnum item. struct TypeEnumItem { - Token: &lex::Token + Token: &token::Token Ident: str Kind: &TypeSymbol } // TypeEnum. struct TypeEnum { - Token: &lex::Token + Token: &token::Token Public: bool Ident: str Items: []&TypeEnumItem diff --git a/std/jule/sema/eval.jule b/std/jule/sema/eval.jule index a9cfb41b1..7a5884439 100644 --- a/std/jule/sema/eval.jule +++ b/std/jule/sema/eval.jule @@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use conv for std::conv -use path for std::fs::path -use ast for std::jule::ast -use build for std::jule::build -use constant for std::jule::constant -use lit for std::jule::constant::lit -use lex for std::jule::lex -use types for std::jule::types -use mod for std::jule::internal::mod -use strings for std::strings +use "std/conv" +use "std/fs/path" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/constant/lit" +use "std/jule/internal/mod" +use "std/jule/token" +use "std/jule/types" +use "std/strings" +use "std/unsafe" // Value data. struct Data { @@ -89,7 +89,7 @@ struct eval { } impl eval { - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.s.pushErr(token, fmt, args...) } @@ -158,7 +158,7 @@ impl eval { fn litStr(self, &l: &ast::LitExpr): &Data { mut s := "" - if lex::IsRawStr(l.Value) { + if token::IsRawStr(l.Value) { s = lit::ToRawStr(l.Value) } else { s = lit::ToStr(l.Value) @@ -261,7 +261,7 @@ impl eval { fn litNum(mut self, &l: &ast::LitExpr): &Data { match { - | lex::IsFloat(l.Value): + | token::IsFloat(l.Value): ret self.litFloat(l) |: ret self.litInt(l) @@ -270,11 +270,11 @@ impl eval { fn evalLit(mut self, lit: &ast::LitExpr): &Data { match { - | lex::IsStr(lit.Value): + | token::IsStr(lit.Value): ret self.litStr(lit) - | lex::IsRune(lit.Value): + | token::IsRune(lit.Value): ret self.litRune(lit) - | lex::IsNum(lit.Value): + | token::IsNum(lit.Value): ret self.litNum(lit) |: ret nil @@ -382,7 +382,7 @@ impl eval { } } - fn evalEnum(mut self, mut enm: &Enum, errorToken: &lex::Token): &Data { + fn evalEnum(mut self, mut enm: &Enum, errorToken: &token::Token): &Data { if !self.s.isAccessibleDefine(enm.Public, enm.Token) { self.pushErr(errorToken, build::LogMsg.IdentIsNotAccessible, enm.Ident) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -400,7 +400,7 @@ impl eval { } } - fn evalTypeEnum(mut self, mut enm: &TypeEnum, errorToken: &lex::Token): &Data { + fn evalTypeEnum(mut self, mut enm: &TypeEnum, errorToken: &token::Token): &Data { if !self.s.isAccessibleDefine(enm.Public, enm.Token) { self.pushErr(errorToken, build::LogMsg.IdentIsNotAccessible, enm.Ident) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -423,7 +423,7 @@ impl eval { ret d } - fn evalStruct(mut self, mut s: &Struct, mut errorToken: &lex::Token): &Data { + fn evalStruct(mut self, mut s: &Struct, mut errorToken: &token::Token): &Data { if !self.s.isAccessibleDefine(s.Public, s.Token) { self.pushErr(errorToken, build::LogMsg.IdentIsNotAccessible, s.Ident) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -461,7 +461,7 @@ impl eval { } } - fn checkDeprecated(mut self, mut &directives: []&ast::Directive, tok: &lex::Token) { + fn checkDeprecated(mut self, mut &directives: []&ast::Directive, tok: &token::Token) { if self.isUnsafe() { ret } @@ -477,7 +477,7 @@ impl eval { } } - fn evalFn(mut self, mut f: &Fn, errorToken: &lex::Token): &Data { + fn evalFn(mut self, mut f: &Fn, errorToken: &token::Token): &Data { if !self.s.isAccessibleDefine(f.Public, f.Token) { self.pushErr(errorToken, build::LogMsg.IdentIsNotAccessible, f.Ident) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -502,7 +502,7 @@ impl eval { ret self.evalFnIns(ins) } - fn pushIllegalCycleError(mut self, &v1: &Var, &v2: &Var, mut &message: strings::StrBuilder) { + fn pushIllegalCycleError(mut self, &v1: &Var, &v2: &Var, mut &message: strings::Builder) { const Padding = 7 refersTo := build::Logf(build::LogMsg.RefersTo, v1.Ident, v2.Ident) buf := unsafe { message.Buf() } @@ -512,7 +512,7 @@ impl eval { message.Write(buf) } - fn checkCrossCycle(mut self, &v: &Var, mut &message: strings::StrBuilder): bool { + fn checkCrossCycle(mut self, &v: &Var, mut &message: strings::Builder): bool { for _, d in v.Depends { if d == self.owner { self.pushIllegalCycleError(v, d, message) @@ -529,7 +529,7 @@ impl eval { // Checks owner illegal cycles. // Appends depend to depends if there is no illegal cycle. // Returns true if e.owner is nil. - fn checkIllegalCycles(mut self, mut &v: &Var, declToken: &lex::Token): (ok: bool) { + fn checkIllegalCycles(mut self, mut &v: &Var, declToken: &token::Token): (ok: bool) { // Skip cycle checking if owner is nil or not global. if self.owner == nil || self.owner.Scope != nil { ret true @@ -542,7 +542,7 @@ impl eval { ret false } - mut message := strings::StrBuilder.New(1 << 5) + mut message := strings::Builder.New(1 << 5) if !self.checkCrossCycle(v, message) { mut errMsg := message.Str() @@ -557,7 +557,7 @@ impl eval { ret true } - fn evalVar(mut self, mut v: &Var, errorToken: &lex::Token): &Data { + fn evalVar(mut self, mut v: &Var, errorToken: &token::Token): &Data { if !self.s.isAccessibleDefine(v.Public, v.Token) { self.pushErr(errorToken, build::LogMsg.IdentIsNotAccessible, v.Ident) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -680,7 +680,7 @@ impl eval { ret d } - fn evalTypeAlias(mut self, mut ta: &TypeAlias, errorToken: &lex::Token): &Data { + fn evalTypeAlias(mut self, mut ta: &TypeAlias, errorToken: &token::Token): &Data { if !self.s.isAccessibleDefine(ta.Public, ta.Token) { self.pushErr(errorToken, build::LogMsg.IdentIsNotAccessible, ta.Ident) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -719,7 +719,7 @@ impl eval { ret d } - fn evalDef(mut self, mut &def: any, mut ident: &lex::Token): &Data { + fn evalDef(mut self, mut &def: any, mut ident: &token::Token): &Data { match type def { | &Var: ret self.evalVar((&Var)(def), ident) @@ -934,7 +934,7 @@ impl eval { ret d } - fn checkIntegerIndexingByData(mut self, mut &d: &Data, mut token: &lex::Token): bool { + fn checkIntegerIndexingByData(mut self, mut &d: &Data, mut token: &token::Token): bool { errKey := checkDataForIntegerIndexing(self.s, d, token, self.getOwnerRefers()) match errKey { | build::LogMsg.Empty: @@ -1110,7 +1110,7 @@ impl eval { | &ast::UnaryExpr: mut u := (&ast::UnaryExpr)(expr.Kind) match u.Op.Id { - | lex::TokenId.Star: + | token::Id.Star: mut kind := new(ast::PtrTypeDecl) mut _generics := make([]&ast::TypeDecl, 0, 1) self.pushGenericsFromData(_generics, u.Expr) @@ -1119,7 +1119,7 @@ impl eval { Token: expr.Token, Kind: kind, }) - | lex::TokenId.Amper: + | token::Id.Amper: mut kind := new(ast::SptrTypeDecl) mut _generics := make([]&ast::TypeDecl, 0, 1) self.pushGenericsFromData(_generics, u.Expr) @@ -1152,8 +1152,8 @@ impl eval { ret false } } - | &ast::NsSelectionExpr: - mut ns := (&ast::NsSelectionExpr)(expr.Kind) + | &ast::NamespaceExpr: + mut ns := (&ast::NamespaceExpr)(expr.Kind) mut decl := &ast::IdentTypeDecl{ Token: ns.Ident, Ident: ns.Ident.Kind, @@ -1161,7 +1161,7 @@ impl eval { generics = append(generics, &ast::TypeDecl{ Token: decl.Token, Kind: &ast::NamespaceTypeDecl{ - Idents: ns.Ns, + Namespace: ns.Namespace, Kind: &ast::TypeDecl{ Token: decl.Token, Kind: decl, @@ -1192,8 +1192,8 @@ impl eval { Token: expr.Token, Ident: expr.Ident, } - | &ast::NsSelectionExpr: - mut expr := (&ast::NsSelectionExpr)(i.Expr.Kind) + | &ast::NamespaceExpr: + mut expr := (&ast::NamespaceExpr)(i.Expr.Kind) decl = &ast::IdentTypeDecl{ Token: expr.Ident, Ident: expr.Ident.Kind, @@ -1218,7 +1218,7 @@ impl eval { // Checks new generics function instance. // If instance is already exist, f will point to exist instantantiation. - fn checkGenericFn(mut &self, mut &f: &FnIns, mut &et: &lex::Token, mut &model: ExprModel): (ok: bool, exist: bool) { + fn checkGenericFn(mut &self, mut &f: &FnIns, mut &et: &token::Token, mut &model: ExprModel): (ok: bool, exist: bool) { mut old := f ok, exist = self.s.checkGenericFn(f, et) if ok && exist { @@ -1354,7 +1354,7 @@ impl eval { Constant: constant::Const.NewI64(0), Kind: primInt, } - l.Constant.Kind = PrimKind.Int + l.Constant.Kind = types::Kind.Int l.Model = l.Constant } @@ -1479,7 +1479,7 @@ impl eval { ret d } - fn castPtr(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castPtr(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { d.Constant = nil d.untyped = false sptr := d.Kind.Sptr() @@ -1501,7 +1501,7 @@ impl eval { } } - fn castStruct(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castStruct(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { d.Constant = nil d.untyped = false mut tr := d.Kind.Trait() @@ -1518,7 +1518,7 @@ impl eval { } } - fn castRef(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castRef(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { d.Constant = nil d.untyped = false mut sptr := t.Sptr() @@ -1541,7 +1541,7 @@ impl eval { self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, d.Kind.Str(), t.Str()) } - fn castSlc(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castSlc(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { c := d.Constant d.Constant = nil d.untyped = false @@ -1596,7 +1596,7 @@ impl eval { } } - fn castStr(mut self, mut d: &Data, errorToken: &lex::Token) { + fn castStr(mut self, mut d: &Data, errorToken: &token::Token) { if d.Kind.Enum() != nil { mut e := d.Kind.Enum() if e.Kind.Kind.Prim() != nil && e.Kind.Kind.Prim().IsStr() { @@ -1610,7 +1610,7 @@ impl eval { if d.Kind.Prim() != nil { prim := d.Kind.Prim() if !prim.IsU8() && !prim.IsI32() { - self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, PrimKind.Str, d.Kind.Str()) + self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, types::Kind.Str, d.Kind.Str()) ret } // Cast constant expressions. @@ -1631,19 +1631,19 @@ impl eval { mut s := d.Kind.Slc() if s == nil { - self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, PrimKind.Str, d.Kind.Str()) + self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, types::Kind.Str, d.Kind.Str()) ret } mut t := s.Elem prim := t.Prim() if prim == nil || (!prim.IsU8() && !prim.IsI32()) { - self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, PrimKind.Str, d.Kind.Str()) + self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, types::Kind.Str, d.Kind.Str()) ret } } - fn castInt(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castInt(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { if d.IsConst() { prim := t.Prim() match { @@ -1689,7 +1689,7 @@ impl eval { self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, d.Kind.Str(), t.Str()) } - fn castNum(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castNum(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { if d.IsConst() { prim := t.Prim() match { @@ -1720,11 +1720,11 @@ impl eval { self.pushErr(errorToken, build::LogMsg.TypeNotSupportsCastingTo, d.Kind.Str(), t.Str()) } - fn castPrim(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &lex::Token) { + fn castPrim(mut self, mut t: &TypeKind, mut d: &Data, errorToken: &token::Token) { prim := t.Prim() match { | prim.IsAny(): - panic("eval: castPrim: any case should be unreachable in this routine") + panic("sema: castPrim: any case should be unreachable in this routine") | prim.IsStr(): self.castStr(d, errorToken) | types::IsInt(prim.Str()): @@ -1745,7 +1745,7 @@ impl eval { d.Model = d.Constant } - fn castTypeEnum(mut self, mut &t: &TypeKind, mut &d: &Data, mut &errorToken: &lex::Token) { + fn castTypeEnum(mut self, mut &t: &TypeKind, mut &d: &Data, mut &errorToken: &token::Token) { n := len(self.s.errors) if !self.s.checkTypeCompatibility(d.Kind, t, errorToken) { self.s.errors = self.s.errors[:n] @@ -1755,7 +1755,7 @@ impl eval { d.untyped = false } - fn castTypeEnumT(mut self, mut &t: &TypeKind, mut &d: &Data, mut &errorToken: &lex::Token) { + fn castTypeEnumT(mut self, mut &t: &TypeKind, mut &d: &Data, mut &errorToken: &token::Token) { n := len(self.s.errors) if !self.s.checkTypeCompatibility(t, d.Kind, errorToken) { self.s.errors = self.s.errors[:n] @@ -1765,7 +1765,7 @@ impl eval { d.untyped = false } - fn evalCastByTypeNData(mut self, mut t: &TypeKind, mut d: &Data, mut errorToken: &lex::Token): &Data { + fn evalCastByTypeNData(mut self, mut t: &TypeKind, mut d: &Data, mut errorToken: &token::Token): &Data { if d != nil && d.Decl { self.pushErr(errorToken, build::LogMsg.InvalidExpr) ret nil @@ -1842,7 +1842,7 @@ impl eval { ret d } - fn evalCastT(mut &self, mut &t: &TypeKind, mut &e: &ast::Expr, mut &et: &lex::Token): &Data { + fn evalCastT(mut &self, mut &t: &TypeKind, mut &e: &ast::Expr, mut &et: &token::Token): &Data { mut prefix := self.prefix self.prefix = nil defer { self.prefix = prefix } @@ -1868,17 +1868,13 @@ impl eval { ret self.evalCastT(t.Kind, c.Expr, c.Kind.Token) } - fn evalNsSelection(mut self, mut s: &ast::NsSelectionExpr): &Data { - path := buildLinkPathByTokens(s.Ns) + fn evalNamespace(mut self, mut s: &ast::NamespaceExpr): &Data { mut imp := self.lookup.SelectPackage(fn(imp: &ImportInfo): bool { - if len(s.Ns) == 1 && imp.Alias == path { - ret true - } - ret imp.LinkPath == path && imp.isAccessibleViaSelection() + ret imp.Alias == s.Namespace.Kind }) if imp == nil { - self.pushErr(s.Ns[0], build::LogMsg.NamespaceNotExist, path) + self.pushErr(s.Namespace, build::LogMsg.NamespaceNotExist, s.Namespace.Kind) ret nil } @@ -1895,7 +1891,7 @@ impl eval { } fn evalStructLitExplicit(mut &self, mut s: &StructIns, - mut exprs: []&ast::Expr, mut errorToken: &lex::Token): &Data { + mut exprs: []&ast::Expr, mut errorToken: &token::Token): &Data { ok := self.s.checkGenericQuantity(len(s.Decl.Generics), len(s.Generics), errorToken) if !ok { ret nil @@ -2015,7 +2011,7 @@ impl eval { d.Mutable = true } - fn checkFnOfConcurrentCall(mut self, &f: &FnIns, errorToken: &lex::Token) { + fn checkFnOfConcurrentCall(mut self, &f: &FnIns, errorToken: &token::Token) { if self.isUnsafe() { ret } @@ -2219,7 +2215,7 @@ impl eval { | &ast::IdentExpr: // Use fc.expr.Token.Kind instead of casting. // Same thing, but more efficient and performant. - if fc.Expr.Token.Kind == lex::TokenKind.Error { + if fc.Expr.Token.Kind == token::Kind.Error { ret builtinCallerError(self, fc) } } @@ -2243,7 +2239,7 @@ impl eval { ret d } - fn evalEnumStatic(mut self, mut enm: &Enum, mut ident: &lex::Token): &Data { + fn evalEnumStatic(mut self, mut enm: &Enum, mut ident: &token::Token): &Data { mut item := enm.FindItem(ident.Kind) if item == nil { self.pushErr(ident, build::LogMsg.ObjHaveNotIdent, enm.Ident, ident.Kind) @@ -2251,7 +2247,7 @@ impl eval { ret evalEnumStatic(self.s, enm, item, ident, self.getOwnerRefers()) } - fn evalTypeEnumStatic(mut self, mut enm: &TypeEnum, ident: &lex::Token): &Data { + fn evalTypeEnumStatic(mut self, mut enm: &TypeEnum, ident: &token::Token): &Data { mut item := enm.FindItem(ident.Kind) if item == nil { self.pushErr(ident, build::LogMsg.ObjHaveNotIdent, enm.Ident, ident.Kind) @@ -2274,7 +2270,7 @@ impl eval { } } - fn evalStructStatic(mut self, mut s: &StructIns, ident: &lex::Token): &Data { + fn evalStructStatic(mut self, mut s: &StructIns, ident: &token::Token): &Data { mut d := new(Data) // Method. @@ -2309,7 +2305,7 @@ impl eval { ret nil } - fn evalTraitSubIdent(mut self, mut d: &Data, mut trt: &Trait, mut ident: &lex::Token): &Data { + fn evalTraitSubIdent(mut self, mut d: &Data, mut trt: &Trait, mut ident: &token::Token): &Data { mut f := trt.FindMethod(ident.Kind) if f == nil { self.pushErr(ident, build::LogMsg.ObjHaveNotIdent, trt.Ident, ident.Kind) @@ -2331,7 +2327,7 @@ impl eval { // This method evaluates expressions, will not check public availability. // The tok parameter should be identifier to accessed. - fn evalStructSubIdentField(mut self, mut &d: &Data, mut &s: &StructIns, mut &tok: &lex::Token, mut &f: &FieldIns): &Data { + fn evalStructSubIdentField(mut self, mut &d: &Data, mut &s: &StructIns, mut &tok: &token::Token, mut &f: &FieldIns): &Data { mut model := &StructSubIdentExprModel{ Token: tok, Expr: new(Data, *d), @@ -2356,7 +2352,7 @@ impl eval { // This method evaluates expressions, will not check public availability. // The tok parameter should be identifier to accessed. - fn evalStructSubIdentMethod(mut self, mut &d: &Data, mut &s: &StructIns, mut &tok: &lex::Token, mut &m: &Fn, ref: bool): &Data { + fn evalStructSubIdentMethod(mut self, mut &d: &Data, mut &s: &StructIns, mut &tok: &token::Token, mut &m: &Fn, ref: bool): &Data { if m.Params[0].IsRef() && !ref { self.pushErr(tok, build::LogMsg.RefMethodUsedWithNotRefInstance) } @@ -2401,8 +2397,8 @@ impl eval { ret self.evalStructSubIdentMethod(d, s, si.Ident, m, ref) } - fn evalIntTypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.Int + fn evalIntTypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.Int match ident.Kind { | "Max": mut c := constant::Const.NewI64(types::MaxI(kind)) @@ -2428,8 +2424,8 @@ impl eval { } } - fn evalUintTypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.Uint + fn evalUintTypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.Uint match ident.Kind { | "Max": mut c := constant::Const.NewU64(types::MaxU(kind)) @@ -2446,8 +2442,8 @@ impl eval { } } - fn evalI8TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.I8 + fn evalI8TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.I8 const min = types::MinI8 const max = types::MaxI8 match ident.Kind { @@ -2475,8 +2471,8 @@ impl eval { } } - fn evalI16TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.I16 + fn evalI16TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.I16 const min = types::MinI16 const max = types::MaxI16 match ident.Kind { @@ -2504,8 +2500,8 @@ impl eval { } } - fn evalI32TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.I32 + fn evalI32TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.I32 const min = types::MinI32 const max = types::MaxI32 match ident.Kind { @@ -2533,8 +2529,8 @@ impl eval { } } - fn evalI64TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.I64 + fn evalI64TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.I64 const min = types::MinI64 const max = types::MaxI64 match ident.Kind { @@ -2562,8 +2558,8 @@ impl eval { } } - fn evalU8TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.U8 + fn evalU8TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.U8 const max = types::MaxU8 match ident.Kind { | "Max": @@ -2581,8 +2577,8 @@ impl eval { } } - fn evalU16TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.U16 + fn evalU16TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.U16 const max = types::MaxU16 match ident.Kind { | "Max": @@ -2600,8 +2596,8 @@ impl eval { } } - fn evalU32TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.U32 + fn evalU32TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.U32 const max = types::MaxU32 match ident.Kind { | "Max": @@ -2619,8 +2615,8 @@ impl eval { } } - fn evalU64TypeStatic(mut self, ident: &lex::Token): &Data { - const kind: str = PrimKind.U64 + fn evalU64TypeStatic(mut self, ident: &token::Token): &Data { + const kind: str = types::Kind.U64 const max = types::MaxU64 match ident.Kind { | "Max": @@ -2638,8 +2634,8 @@ impl eval { } } - fn evalF32TypeStatic(mut self, ident: &lex::Token): &Data { - const kind = PrimKind.F32 + fn evalF32TypeStatic(mut self, ident: &token::Token): &Data { + const kind = types::Kind.F32 const max = types::MaxF32 const min = types::MinF32 const smallestNonZero = types::SmallestNonZeroF32 @@ -2677,8 +2673,8 @@ impl eval { } } - fn evalF64TypeStatic(mut self, ident: &lex::Token): &Data { - const kind = PrimKind.F64 + fn evalF64TypeStatic(mut self, ident: &token::Token): &Data { + const kind = types::Kind.F64 const max = types::MaxF64 const min = types::MinF64 const smallestNonZero = types::SmallestNonZeroF64 @@ -2716,31 +2712,31 @@ impl eval { } } - fn evalPrimStatic(mut self, kind: str, ident: &lex::Token): &Data { + fn evalPrimStatic(mut self, kind: str, ident: &token::Token): &Data { match kind { - | PrimKind.Int: + | types::Kind.Int: ret self.evalIntTypeStatic(ident) - | PrimKind.Uint: + | types::Kind.Uint: ret self.evalUintTypeStatic(ident) - | PrimKind.I8: + | types::Kind.I8: ret self.evalI8TypeStatic(ident) - | PrimKind.I16: + | types::Kind.I16: ret self.evalI16TypeStatic(ident) - | PrimKind.I32: + | types::Kind.I32: ret self.evalI32TypeStatic(ident) - | PrimKind.I64: + | types::Kind.I64: ret self.evalI64TypeStatic(ident) - | PrimKind.U8: + | types::Kind.U8: ret self.evalU8TypeStatic(ident) - | PrimKind.U16: + | types::Kind.U16: ret self.evalU16TypeStatic(ident) - | PrimKind.U32: + | types::Kind.U32: ret self.evalU32TypeStatic(ident) - | PrimKind.U64: + | types::Kind.U64: ret self.evalU64TypeStatic(ident) - | PrimKind.F32: + | types::Kind.F32: ret self.evalF32TypeStatic(ident) - | PrimKind.F64: + | types::Kind.F64: ret self.evalF64TypeStatic(ident) |: self.pushErr(ident, build::LogMsg.TypeHaveNotIdent, kind, ident.Kind) @@ -2804,7 +2800,7 @@ impl eval { } fn evalObjSubIdent(mut self, mut d: &Data, mut si: &ast::SubIdentExpr): &Data { - if lex::IsIgnoreIdent(si.Ident.Kind) { + if token::IsIgnoreIdent(si.Ident.Kind) { self.pushErr(si.Ident, build::LogMsg.InvalidSyntax) ret nil } @@ -3029,8 +3025,8 @@ impl eval { ret self.evalSlicing((&ast::SlicingExpr)(kind)) | &ast::CastExpr: ret self.evalCast((&ast::CastExpr)(kind)) - | &ast::NsSelectionExpr: - ret self.evalNsSelection((&ast::NsSelectionExpr)(kind)) + | &ast::NamespaceExpr: + ret self.evalNamespace((&ast::NamespaceExpr)(kind)) | &ast::StructLit: ret self.evalStructLit((&ast::StructLit)(kind)) | &ast::TypeDecl: @@ -3189,7 +3185,7 @@ impl unaryEval { | self.d.Constant.IsU64(): self.d.Constant.SetI64(-self.d.Constant.AsI64()) |: - panic("unimplemented constant type for unary.minus, this panic call should be unreachable") + panic("sema: unimplemented constant type for unary.minus, this panic call should be unreachable") } // Do not self model for constant expressions. It's a overhead, // because model will be changed to constant by following algorithm. @@ -3234,7 +3230,7 @@ impl unaryEval { | self.d.Constant.IsU64(): self.d.Constant.SetI64(+self.d.Constant.AsI64()) |: - panic("unimplemented constant type for unary.plus, this panic call should be unreachable") + panic("sema: unimplemented constant type for unary.plus, this panic call should be unreachable") } // Do not self model for constant expressions. It's a overhead, // because model will be changed to constant by following algorithm. @@ -3277,7 +3273,7 @@ impl unaryEval { | self.d.Constant.IsU64(): self.d.Constant.SetU64(^self.d.Constant.ReadU64()) |: - panic("unimplemented constant type for unary.caret, this panic call should be unreachable") + panic("sema: unimplemented constant type for unary.caret, this panic call should be unreachable") } // Do not self model for constant expressions. It's a overhead, // because model will be changed to constant by following algorithm. @@ -3305,7 +3301,7 @@ impl unaryEval { | self.d.Constant.IsBool(): self.d.Constant.SetBool(!self.d.Constant.ReadBool()) |: - panic("unimplemented constant type for unary.excl, this panic call should be unreachable") + panic("sema: unimplemented constant type for unary.excl, this panic call should be unreachable") } // Do not self model for constant expressions. It's a overhead, // because model will be changed to constant by following algorithm. @@ -3384,10 +3380,10 @@ impl unaryEval { errorToken: self.u.Op, } match self.u.Op.Id { - | lex::TokenId.Star: + | token::Id.Star: self.d.Kind = &TypeKind{Kind: tc.buildPtrFromType(self.d.Kind)} self.d.Model = self.d.Kind - | lex::TokenId.Amper: + | token::Id.Amper: self.d.Kind = &TypeKind{Kind: tc.buildSptrFromType(self.d.Kind)} self.d.Model = self.d.Kind |: @@ -3400,8 +3396,8 @@ impl unaryEval { fn evalData(mut self) { match self.u.Op.Id { - | lex::TokenId.Star - | lex::TokenId.Amper: + | token::Id.Star + | token::Id.Amper: mut prefix := self.e.prefix self.e.prefix = nil self.d = self.e.eval(self.u.Expr) @@ -3424,17 +3420,17 @@ impl unaryEval { kind := self.d.Kind match self.u.Op.Id { - | lex::TokenId.Minus: + | token::Id.Minus: self.minus() - | lex::TokenId.Plus: + | token::Id.Plus: self.plus() - | lex::TokenId.Caret: + | token::Id.Caret: self.caret() - | lex::TokenId.Excl: + | token::Id.Excl: self.excl() - | lex::TokenId.Star: + | token::Id.Star: self.star() - | lex::TokenId.Amper: + | token::Id.Amper: self.amper() |: self.d = nil @@ -3455,7 +3451,7 @@ struct binaryEval { e: &eval l: &Data r: &Data - op: &lex::Token + op: &token::Token } impl binaryEval { @@ -3465,7 +3461,7 @@ impl binaryEval { } } - static fn new(mut e: &eval, mut op: &lex::Token): binaryEval { + static fn new(mut e: &eval, mut op: &token::Token): binaryEval { ret binaryEval{ e: e, op: op, @@ -3481,25 +3477,25 @@ impl binaryEval { fn checkStructCommonOperatorCompatibility(mut self): bool { let mut overload: &FnIns = nil match self.op.Id { - | lex::TokenId.Shl: + | token::Id.Shl: overload = self.l.Kind.Struct().Operators.Shl - | lex::TokenId.Shr: + | token::Id.Shr: overload = self.l.Kind.Struct().Operators.Shr - | lex::TokenId.Plus: + | token::Id.Plus: overload = self.l.Kind.Struct().Operators.Add - | lex::TokenId.Minus: + | token::Id.Minus: overload = self.l.Kind.Struct().Operators.Sub - | lex::TokenId.Solidus: + | token::Id.Solidus: overload = self.l.Kind.Struct().Operators.Div - | lex::TokenId.Star: + | token::Id.Star: overload = self.l.Kind.Struct().Operators.Mul - | lex::TokenId.Percent: + | token::Id.Percent: overload = self.l.Kind.Struct().Operators.Mod - | lex::TokenId.Amper: + | token::Id.Amper: overload = self.l.Kind.Struct().Operators.BitAnd - | lex::TokenId.Vline: + | token::Id.Vline: overload = self.l.Kind.Struct().Operators.BitOr - | lex::TokenId.Caret: + | token::Id.Caret: overload = self.l.Kind.Struct().Operators.BitXor |: self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, self.l.Kind.Str()) @@ -3523,14 +3519,14 @@ impl binaryEval { } mut l := self.l.Kind.comptimeTypeInfo() match self.op.Id { - | lex::TokenId.Eqs: + | token::Id.Eqs: mut constant := constant::Const.NewBool(l.base.Equal(r.base)) ret &Data{ Kind: primBool, Constant: constant, Model: constant, } - | lex::TokenId.NotEq: + | token::Id.NotEq: mut constant := constant::Const.NewBool(!l.base.Equal(r.base)) ret &Data{ Kind: primBool, @@ -3550,8 +3546,8 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: ret &Data{ Kind: primBool, } @@ -3564,8 +3560,8 @@ impl binaryEval { fn evalEnum(mut self): &Data { mut enm := self.l.Kind.Enum() match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: mut rkind := self.r.Kind if self.r.Kind.Enum() != nil { rkind = self.r.Kind.Enum().Kind.Kind @@ -3584,10 +3580,10 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Gt - | lex::TokenId.Lt - | lex::TokenId.GtEq - | lex::TokenId.LtEq: + | token::Id.Gt + | token::Id.Lt + | token::Id.GtEq + | token::Id.LtEq: if !types::IsNum(enm.Kind.Kind.Str()) { self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, enm.Ident) ret nil @@ -3595,7 +3591,7 @@ impl binaryEval { ret &Data{ Kind: primBool, } - | lex::TokenId.Amper: + | token::Id.Amper: first := enm.Items[0] match { | first.Value.Data.Constant.IsI64(): @@ -3609,15 +3605,15 @@ impl binaryEval { } goto err |: - panic("unimplemented enum type, this panic call should be unreachable") + panic("sema: unimplemented enum type, this panic call should be unreachable") } err: self.e.pushErr(self.op, build::LogMsg.AmperOpForEnum, enm.Ident, self.op.Kind) self.e.pushSuggestion(build::LogMsg.DefineZeroDefaultToUseAmper) next: fall - | lex::TokenId.Vline - | lex::TokenId.Caret: + | token::Id.Vline + | token::Id.Caret: if enm.Kind.Kind.Prim() == nil || !types::IsInt(enm.Kind.Kind.Prim().Str()) { self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, enm.Ident) } @@ -3635,8 +3631,8 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: ret &Data{ Kind: primBool, } @@ -3652,8 +3648,8 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: ret &Data{ Kind: primBool, } @@ -3665,20 +3661,20 @@ impl binaryEval { fn evalPtr(mut self): &Data { match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq - | lex::TokenId.Lt - | lex::TokenId.Gt - | lex::TokenId.LtEq - | lex::TokenId.GtEq: + | token::Id.Eqs + | token::Id.NotEq + | token::Id.Lt + | token::Id.Gt + | token::Id.LtEq + | token::Id.GtEq: if !self.checkTypeCompatibility() { ret nil } ret &Data{ Kind: primBool, } - | lex::TokenId.Plus - | lex::TokenId.Minus: + | token::Id.Plus + | token::Id.Minus: if self.l.Kind.Ptr() == nil { self.l, self.r = self.r, self.l } @@ -3702,15 +3698,15 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: if self.e.s.meta.runtime != nil { // Add instance to relevant runtime function for array element type if not exist. mut f := runtimeFindFn(self.e.s.meta.runtime, runtimeFunc.arrayCmp).instanceForce() f.Generics = append(f.Generics, &InsGeneric{Kind: self.l.Kind.Arr().Elem}) ok, _ := self.e.s.checkGenericFn(f, self.op) if !ok { - panic("arrayCmp evaluation failed, this is an implementation mistake") + panic("sema: arrayCmp evaluation failed, this is an implementation mistake") } self.e.pushReference[&FnIns](f) } @@ -3725,7 +3721,7 @@ impl binaryEval { fn evalStruct(mut self): &Data { match self.op.Id { - | lex::TokenId.Gt: + | token::Id.Gt: if self.l.Kind.Struct().Operators.Gt == nil { self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, self.l.Kind.Str()) ret nil @@ -3733,7 +3729,7 @@ impl binaryEval { ret &Data{ Kind: primBool, } - | lex::TokenId.GtEq: + | token::Id.GtEq: if self.l.Kind.Struct().Operators.GtEq == nil { self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, self.l.Kind.Str()) ret nil @@ -3741,7 +3737,7 @@ impl binaryEval { ret &Data{ Kind: primBool, } - | lex::TokenId.Lt: + | token::Id.Lt: if self.l.Kind.Struct().Operators.Lt == nil { self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, self.l.Kind.Str()) ret nil @@ -3749,7 +3745,7 @@ impl binaryEval { ret &Data{ Kind: primBool, } - | lex::TokenId.LtEq: + | token::Id.LtEq: if self.l.Kind.Struct().Operators.LtEq == nil { self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, self.l.Kind.Str()) ret nil @@ -3757,8 +3753,8 @@ impl binaryEval { ret &Data{ Kind: primBool, } - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: if !self.checkTypeCompatibility() { ret nil } @@ -3779,8 +3775,8 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: ret &Data{ Kind: primBool, } @@ -3792,14 +3788,14 @@ impl binaryEval { fn evalAny(mut self): &Data { match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq: + | token::Id.Eqs + | token::Id.NotEq: applyImplicitCast(self.e.s, self.l.Kind, self.r, self.op, self.e.getOwnerRefers()) ret &Data{ Kind: primBool, } |: - self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, PrimKind.Any) + self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, types::Kind.Any) ret nil } } @@ -3810,10 +3806,10 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq - | lex::TokenId.DblAmper - | lex::TokenId.DblVline: + | token::Id.Eqs + | token::Id.NotEq + | token::Id.DblAmper + | token::Id.DblVline: ret self.l |: self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, self.l.Kind.Str()) @@ -3823,25 +3819,25 @@ impl binaryEval { fn evalStr(mut self): &Data { mut rk := self.r.Kind.Str() - if rk != PrimKind.Str { - self.e.pushErr(self.op, build::LogMsg.IncompatibleTypes, PrimKind.Str, rk) + if rk != types::Kind.Str { + self.e.pushErr(self.op, build::LogMsg.IncompatibleTypes, types::Kind.Str, rk) ret nil } match self.op.Id { - | lex::TokenId.Plus: + | token::Id.Plus: ret self.l - | lex::TokenId.Eqs - | lex::TokenId.NotEq - | lex::TokenId.Lt - | lex::TokenId.Gt - | lex::TokenId.GtEq - | lex::TokenId.LtEq: + | token::Id.Eqs + | token::Id.NotEq + | token::Id.Lt + | token::Id.Gt + | token::Id.GtEq + | token::Id.LtEq: ret &Data{ Kind: primBool, } |: - self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, PrimKind.Str) + self.e.pushErr(self.op, build::LogMsg.OperatorNotForJuleType, self.op.Kind, types::Kind.Str) ret nil } } @@ -3872,9 +3868,9 @@ impl binaryEval { ret } match { - | sigAssignable(PrimKind.I64, d): + | sigAssignable(types::Kind.I64, d): d.Constant.SetI64(d.Constant.AsI64()) - | unsigAssignable(PrimKind.U64, d): + | unsigAssignable(types::Kind.U64, d): d.Constant.SetU64(d.Constant.AsU64()) |: self.e.pushErr(self.op, build::LogMsg.ModuloWithNotInt) @@ -3893,17 +3889,17 @@ impl binaryEval { if self.l.IsConst() && self.l.untyped { ret true } - if lk == types::TypeKind.F32 { + if lk == types::Kind.F32 { if self.r.IsConst() && self.r.untyped { ret floatAssignable(lk, self.r) } - ret rk == types::TypeKind.F32 + ret rk == types::Kind.F32 } - if lk == types::TypeKind.F64 { + if lk == types::Kind.F64 { if self.r.IsConst() && self.r.untyped { ret floatAssignable(lk, self.r) } - ret rk == types::TypeKind.F64 + ret rk == types::Kind.F64 } if self.r.IsConst() && self.r.untyped { ret intAssignable(lk, self.r) @@ -3937,10 +3933,10 @@ impl binaryEval { if !self.l.IsConst() || !self.l.untyped { self.e.pushErr(self.op, build::LogMsg.IncompatibleTypes, lk.Kind, rk.Kind) ret nil - } else if intAssignable(PrimKind.I64, self.l) { + } else if intAssignable(types::Kind.I64, self.l) { self.l.Constant.SetI64(self.l.Constant.AsI64()) self.l.Kind = primI64 - } else if intAssignable(PrimKind.U64, self.l) { + } else if intAssignable(types::Kind.U64, self.l) { self.l.Constant.SetU64(self.l.Constant.AsU64()) self.l.Kind = primU64 } @@ -3950,10 +3946,10 @@ impl binaryEval { if !self.r.IsConst() || !self.l.untyped { self.e.pushErr(self.op, build::LogMsg.IncompatibleTypes, lk.Kind, rk.Kind) ret nil - } else if intAssignable(PrimKind.I64, self.r) { + } else if intAssignable(types::Kind.I64, self.r) { self.r.Constant.SetI64(self.r.Constant.AsI64()) self.r.Kind = primI64 - } else if intAssignable(PrimKind.U64, self.r) { + } else if intAssignable(types::Kind.U64, self.r) { self.r.Constant.SetU64(self.r.Constant.AsU64()) self.r.Kind = primU64 } @@ -3978,12 +3974,12 @@ impl binaryEval { // Logicals. match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq - | lex::TokenId.Lt - | lex::TokenId.Gt - | lex::TokenId.GtEq - | lex::TokenId.LtEq: + | token::Id.Eqs + | token::Id.NotEq + | token::Id.Lt + | token::Id.Gt + | token::Id.GtEq + | token::Id.LtEq: self.setTypeToGreater() ret &Data{ Kind: primBool, @@ -3992,18 +3988,18 @@ impl binaryEval { // Arithmetics. match self.op.Id { - | lex::TokenId.Shl - | lex::TokenId.Shr: + | token::Id.Shl + | token::Id.Shr: panic("sema: binary shifting operator handling failed") - | lex::TokenId.Plus - | lex::TokenId.Minus - | lex::TokenId.Star: + | token::Id.Plus + | token::Id.Minus + | token::Id.Star: self.setTypeToGreater() ret self.l - | lex::TokenId.Solidus: + | token::Id.Solidus: self.setTypeToGreater() ret self.l - | lex::TokenId.Percent: + | token::Id.Percent: if !types::IsInt(rk) { self.e.pushErr(self.op, build::LogMsg.IncompatibleTypes, lk, rk) ret nil @@ -4028,12 +4024,12 @@ impl binaryEval { // Logicals. match self.op.Id { - | lex::TokenId.Eqs - | lex::TokenId.NotEq - | lex::TokenId.Lt - | lex::TokenId.Gt - | lex::TokenId.GtEq - | lex::TokenId.LtEq: + | token::Id.Eqs + | token::Id.NotEq + | token::Id.Lt + | token::Id.Gt + | token::Id.GtEq + | token::Id.LtEq: ret &Data{ Kind: primBool, } @@ -4041,21 +4037,21 @@ impl binaryEval { // Arithmetics. match self.op.Id { - | lex::TokenId.Shl - | lex::TokenId.Shr: + | token::Id.Shl + | token::Id.Shr: panic("sema: binary shifting operator handling failed") - | lex::TokenId.Plus - | lex::TokenId.Minus - | lex::TokenId.Star - | lex::TokenId.Amper - | lex::TokenId.Vline - | lex::TokenId.Caret: + | token::Id.Plus + | token::Id.Minus + | token::Id.Star + | token::Id.Amper + | token::Id.Vline + | token::Id.Caret: self.setTypeToGreater() ret self.l - | lex::TokenId.Solidus: + | token::Id.Solidus: self.setTypeToGreater() ret self.l - | lex::TokenId.Percent: + | token::Id.Percent: self.mod() self.setTypeToGreater() ret self.l @@ -4091,7 +4087,7 @@ impl binaryEval { fn checkSpecialCases(mut self): (ok: bool) { ok = true - comparing := self.op.Id == lex::TokenId.Eqs || self.op.Id == lex::TokenId.NotEq + comparing := self.op.Id == token::Id.Eqs || self.op.Id == token::Id.NotEq if !comparing { ret } @@ -4118,7 +4114,7 @@ impl binaryEval { } // Shift operators. - if self.op.Id == lex::TokenId.Shl || self.op.Id == lex::TokenId.Shr { + if self.op.Id == token::Id.Shl || self.op.Id == token::Id.Shr { ret self.shift() } @@ -4190,32 +4186,32 @@ impl binaryEval { } match self.op.Id { - | lex::TokenId.Eqs: + | token::Id.Eqs: d.Constant = constant::Const.NewBool(self.l.Constant.Eq(*self.r.Constant)) - | lex::TokenId.NotEq: + | token::Id.NotEq: d.Constant = constant::Const.NewBool(!self.l.Constant.Eq(*self.r.Constant)) - | lex::TokenId.DblVline: + | token::Id.DblVline: d.Constant = constant::Const.NewBool(self.l.Constant.Or(*self.r.Constant)) - | lex::TokenId.DblAmper: + | token::Id.DblAmper: d.Constant = constant::Const.NewBool(self.l.Constant.And(*self.r.Constant)) - | lex::TokenId.Gt: + | token::Id.Gt: d.Constant = constant::Const.NewBool(self.l.Constant.Gt(*self.r.Constant)) - | lex::TokenId.Lt: + | token::Id.Lt: d.Constant = constant::Const.NewBool(self.l.Constant.Lt(*self.r.Constant)) - | lex::TokenId.GtEq: + | token::Id.GtEq: d.Constant = constant::Const.NewBool(self.l.Constant.GtEq(*self.r.Constant)) - | lex::TokenId.LtEq: + | token::Id.LtEq: d.Constant = constant::Const.NewBool(self.l.Constant.LtEq(*self.r.Constant)) - | lex::TokenId.Plus: + | token::Id.Plus: _ = self.l.Constant.Add(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Minus: + | token::Id.Minus: _ = self.l.Constant.Sub(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Star: + | token::Id.Star: _ = self.l.Constant.Mul(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Solidus: + | token::Id.Solidus: ok := self.l.Constant.Div(*self.r.Constant) if !ok && self.r.Constant.AsF64() == 0 { self.e.pushErr(self.op, build::LogMsg.DivByZero) @@ -4228,25 +4224,25 @@ impl binaryEval { | types::IsUnsigInt(prim.Kind): d.Constant.SetU64(d.Constant.AsU64()) } - | lex::TokenId.Percent: + | token::Id.Percent: ok := self.l.Constant.Mod(*self.r.Constant) if !ok && self.r.Constant.AsF64() == 0 { self.e.pushErr(self.op, build::LogMsg.DivByZero) } d.Constant = self.l.Constant - | lex::TokenId.Vline: + | token::Id.Vline: _ = self.l.Constant.BitwiseOr(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Amper: + | token::Id.Amper: _ = self.l.Constant.BitwiseAnd(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Caret: + | token::Id.Caret: _ = self.l.Constant.Xor(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Shl: + | token::Id.Shl: _ = self.l.Constant.Lshift(*self.r.Constant) d.Constant = self.l.Constant - | lex::TokenId.Shr: + | token::Id.Shr: _ = self.l.Constant.Rshift(*self.r.Constant) d.Constant = self.l.Constant } @@ -4321,7 +4317,7 @@ impl binaryEval { } fn eval(mut self, mut &op: &ast::BinaryExpr): &Data { - if op.Op.Id == lex::TokenId.Eq { + if op.Op.Id == token::Id.Eq { self.e.pushErr(op.Op, build::LogMsg.AssignInExpr) self.e.pushSuggestion(build::LogMsg.UseImperative) ret nil @@ -4374,16 +4370,16 @@ fn findBuiltinsImport(&ident: str, imp: &ImportInfo): any { // thing for unsigned data and signed kinds. fn fitBitsize(mut &d: &Data) { mut prim := d.Kind.Prim() - z := types::BitsizeOf(prim.Str()) + z := types::BitSizeOf(prim.Str()) match { | d.Constant.IsI64(): - k := types::BitsizeOfInt(d.Constant.ReadI64()) + k := types::BitSizeOfInt(d.Constant.ReadI64()) if k > z || types::IsUnsigInt(prim.Kind) { d.Constant.Kind = types::IntFromBits(k) d.Kind = findBuiltinTypeAlias(d.Constant.Kind).Kind.Kind } | d.Constant.IsU64(): - k := types::BitsizeOfUint(d.Constant.ReadU64()) + k := types::BitSizeOfUint(d.Constant.ReadU64()) if k > z || types::IsSigInt(prim.Kind) { d.Constant.Kind = types::UintFromBits(k) d.Kind = findBuiltinTypeAlias(d.Constant.Kind).Kind.Kind @@ -4393,7 +4389,7 @@ fn fitBitsize(mut &d: &Data) { // z is already equals to biggest bitsize. ret } - k := types::BitsizeOfFloat(d.Constant.ReadF64()) + k := types::BitSizeOfFloat(d.Constant.ReadF64()) if k > z { d.Constant.Kind = types::FloatFromBits(k) d.Kind = findBuiltinTypeAlias(d.Constant.Kind).Kind.Kind @@ -4419,7 +4415,7 @@ fn buildErrorVar(mut &s: &Scope, mut &fc: &ast::FnCallExpr): &Var { Mutable: true, Ident: "error", Token: fc.Token, - Kind: findBuiltinTypeAlias(PrimKind.Any).Kind, + Kind: findBuiltinTypeAlias(types::Kind.Any).Kind, Scope: s, Value: &Value{ Data: new(Data), @@ -4428,15 +4424,6 @@ fn buildErrorVar(mut &s: &Scope, mut &fc: &ast::FnCallExpr): &Var { } fn findBuiltinsSema(&ident: str, mut s: &sema): any { - for (_, mut imp) in s.file.Imports { - if imp.ImportAll || imp.existIdent(ident) { - mut def := findBuiltinsImport(ident, imp) - if def != nil { - ret def - } - } - } - // If package is std, check for internal builtin defines. mut ppath := s.file.File.Dir() if strings::HasPrefix(ppath, build::PathStdlib) { @@ -4444,8 +4431,7 @@ fn findBuiltinsSema(&ident: str, mut s: &sema): any { ppath = ppath[len(build::PathStdlib):] // Add "std" to beginning without separator // because path has separator at beginning. - ppath = "std" + strings::Replace(ppath, str(path::Separator), "::", -1) - + ppath = "std" + strings::Replace(ppath, str(path::Separator), build::ImportPathSep, -1) ret findPackageBuiltinDef(ppath, ident) } @@ -4479,8 +4465,8 @@ fn isPtrArithmeticCompatible(mut &l: &Data, mut &r: &Data): bool { ret l.Kind.Ptr().Elem.Equal(ptr.Elem) } if r.IsConst() && r.untyped { - ret intAssignable(types::TypeKind.Int, r) || - intAssignable(types::TypeKind.Uint, r) + ret intAssignable(types::Kind.Int, r) || + intAssignable(types::Kind.Uint, r) } mut tcc := typeCompatibilityChecker{ @@ -4495,7 +4481,7 @@ fn isPtrArithmeticCompatible(mut &l: &Data, mut &r: &Data): bool { } fn applyRuntimeToStr(mut &s: &sema, mut &from: &TypeKind, mut &to: &TypeKind, - mut &token: &lex::Token, mut refers: &ReferenceStack) { + mut &token: &token::Token, mut refers: &ReferenceStack) { prim := to.Prim() if prim != nil { if prim.IsAny() { @@ -4510,7 +4496,7 @@ fn applyRuntimeToStr(mut &s: &sema, mut &from: &TypeKind, mut &to: &TypeKind, } fn applyCastKindModel(mut &s: &sema, mut &d: &Data, mut &t: &TypeKind, - mut &token: &lex::Token, mut refers: &ReferenceStack) { + mut &token: &token::Token, mut refers: &ReferenceStack) { applyRuntimeToStr(s, d.Kind, t, token, refers) d.Model = &CastingExprModel{ Token: token, @@ -4521,7 +4507,7 @@ fn applyCastKindModel(mut &s: &sema, mut &d: &Data, mut &t: &TypeKind, } fn applyCastKind(mut &s: &sema, mut &d: &Data, mut &t: &TypeKind, - mut &token: &lex::Token, mut refers: &ReferenceStack) { + mut &token: &token::Token, mut refers: &ReferenceStack) { applyCastKindModel(s, d, t, token, refers) d.Kind = t } @@ -4533,7 +4519,7 @@ fn buildVoidData(): &Data { } fn checkDataForIntegerIndexing(mut &s: &sema, mut &d: &Data, - mut &token: &lex::Token, mut refers: &ReferenceStack): (errFmt: build::LogMsg) { + mut &token: &token::Token, mut refers: &ReferenceStack): (errFmt: build::LogMsg) { if d == nil { ret build::LogMsg.Empty } @@ -4549,7 +4535,7 @@ fn checkDataForIntegerIndexing(mut &s: &sema, mut &d: &Data, } | d.Kind.Prim() == nil | d.IsConst() - | types::RealKindOf(d.Kind.Prim().Str()) != types::RealKindOf(PrimKind.Int): + | types::RealKindOf(d.Kind.Prim().Str()) != types::RealKindOf(types::Kind.Int): applyCastKind(s, d, primInt, token, refers) } ret build::LogMsg.Empty @@ -4559,7 +4545,7 @@ fn checkDataForIntegerIndexing(mut &s: &sema, mut &d: &Data, // This is necessary to keep exact same type of enum's field type. // The parameter d should be constant data. fn applyCastModelByEnum(mut &s: &sema, mut &d: &Data, mut e: &Enum, - mut &token: &lex::Token, mut refers: &ReferenceStack) { + mut &token: &token::Token, mut refers: &ReferenceStack) { if e == nil { ret } @@ -4569,7 +4555,7 @@ fn applyCastModelByEnum(mut &s: &sema, mut &d: &Data, mut e: &Enum, fn castConstByType(&t: str, mut &d: &Data) { match { | types::IsSigInt(t): - match types::BitsizeOf(types::RealKindOf(t)) { + match types::BitSizeOf(types::RealKindOf(t)) { | 1 << 6: d.Constant.SetI64(d.Constant.AsI64()) | 1 << 5: @@ -4580,7 +4566,7 @@ fn castConstByType(&t: str, mut &d: &Data) { d.Constant.SetI64(i64(i8(d.Constant.AsI64()))) } | types::IsUnsigInt(t): - match types::BitsizeOf(types::RealKindOf(t)) { + match types::BitSizeOf(types::RealKindOf(t)) { | 1 << 6: d.Constant.SetU64(d.Constant.AsU64()) | 1 << 5: @@ -4591,7 +4577,7 @@ fn castConstByType(&t: str, mut &d: &Data) { d.Constant.SetU64(u64(u8(d.Constant.AsU64()))) } | types::IsFloat(t): - match types::BitsizeOf(types::RealKindOf(t)) { + match types::BitSizeOf(types::RealKindOf(t)) { | 1 << 6: d.Constant.SetF64(d.Constant.AsF64()) | 1 << 5: @@ -4646,7 +4632,7 @@ fn constoa(&c: &constant::Const): str { } fn evalEnumStatic(mut &s: &sema, mut &enm: &Enum, mut &item: &EnumItem, - mut &token: &lex::Token, mut refers: &ReferenceStack): &Data { + mut &token: &token::Token, mut refers: &ReferenceStack): &Data { mut d := &Data{ Kind: &TypeKind{ Kind: enm, @@ -4680,13 +4666,13 @@ fn isLitBased(mut &m: ExprModel): &StructLitExprModel { } } -fn makeImplicitDeref(mut &d: &Data, mut baseToken: &lex::Token) { +fn makeImplicitDeref(mut &d: &Data, mut baseToken: &token::Token) { mut unary := &UnaryExprModel{ Expr: new(Data, *d), - Op: new(lex::Token, *baseToken), + Op: new(token::Token, *baseToken), } - unary.Op.Id = lex::TokenId.Star - unary.Op.Kind = lex::TokenKind.Star + unary.Op.Id = token::Id.Star + unary.Op.Kind = token::Kind.Star d.Model = unary } diff --git a/std/jule/sema/fn.jule b/std/jule/sema/fn.jule index 302f79951..ff47cb663 100644 --- a/std/jule/sema/fn.jule +++ b/std/jule/sema/fn.jule @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex -use strings for std::internal::strings +use "std/internal/strings" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" // Return type. struct RetType { Kind: &TypeSymbol - Idents: []&lex::Token + Idents: []&token::Token } // Parameter. struct Param { - Token: &lex::Token + Token: &token::Token Mutable: bool Variadic: bool Reference: bool @@ -45,7 +45,7 @@ impl Param { struct Fn { sema: &sema - Token: &lex::Token + Token: &token::Token Global: bool Unsafety: bool Public: bool @@ -97,7 +97,7 @@ impl Fn { // Reports whether function is anonymous function. fn IsAnon(self): bool { - ret lex::IsAnonIdent(self.Ident) + ret token::IsAnonIdent(self.Ident) } // Reports whether function has return variable(s). @@ -173,7 +173,7 @@ impl ParamIns { // Implement: Kind // Returns ParamIns's type kind as string. fn Str(self): str { - mut s := strings::StrBuilder.New(1 << 5) + mut s := strings::Builder.New(1 << 5) if self.Decl.Mutable { s.WriteStr("mut ") } @@ -357,7 +357,7 @@ impl FnIns { // Appends identifier to kind of this instance. // Does not appends identifier of this instance to kind if self.Decl is nil reference. fn GetKindStr(self, ident: bool): str { - mut s := strings::StrBuilder.New(1 << 5) + mut s := strings::Builder.New(1 << 5) if self.Decl != nil && self.Decl.Unsafety { s.WriteStr("unsafe ") diff --git a/std/jule/sema/impl.jule b/std/jule/sema/impl.jule index b96517063..fce759413 100644 --- a/std/jule/sema/impl.jule +++ b/std/jule/sema/impl.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast +use "std/jule/ast" // Implementation. struct Impl { diff --git a/std/jule/sema/model.jule b/std/jule/sema/model.jule index 15b00eff7..b592d6687 100644 --- a/std/jule/sema/model.jule +++ b/std/jule/sema/model.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex -use constant for std::jule::constant +use "std/jule/constant" +use "std/jule/token" // Expression Model:. enum ExprModel: type { @@ -59,19 +59,19 @@ struct OperandExprModel { struct BinaryExprModel { Left: &OperandExprModel Right: &OperandExprModel - Op: &lex::Token + Op: &token::Token } // Unary operation expression Model:. struct UnaryExprModel { Expr: &Data - Op: &lex::Token + Op: &token::Token } // Structure field argument expression Model: for constructors. // For example: &MyStruct{10, false, "-"} struct StructArgExprModel { - Token: &lex::Token + Token: &token::Token Field: &FieldIns Expr: &Data } @@ -91,7 +91,7 @@ struct AllocStructLitExprModel { // Casting expression Model:. // For example: (int)(my_float) struct CastingExprModel { - Token: &lex::Token + Token: &token::Token Expr: &Data Kind: &TypeKind ExprKind: &TypeKind @@ -99,7 +99,7 @@ struct CastingExprModel { // Function call expression Model:. struct FnCallExprModel { - Token: &lex::Token + Token: &token::Token Func: &FnIns IsCo: bool Expr: ExprModel @@ -118,7 +118,7 @@ struct SliceExprModel { // Indexing expression Model:. // For example: my_slice[my_index] struct IndexingExprModel { - Token: &lex::Token + Token: &token::Token Expr: &Data Index: &Data } @@ -146,7 +146,7 @@ struct MapExprModel { // Slicing expression Model:. // For example: mySlice[2:len(mySlice)-5] struct SlicingExprModel { - Token: &lex::Token + Token: &token::Token // Expression to slicing. Expr: ExprModel @@ -163,7 +163,7 @@ struct SlicingExprModel { // Trait sub-ident expression Model:. // For example: my_trait.my_sub_ident struct TraitSubIdentExprModel { - Token: &lex::Token + Token: &token::Token Expr: ExprModel Method: &Fn Trt: &Trait @@ -172,7 +172,7 @@ struct TraitSubIdentExprModel { // Structure sub-ident expression Model:. // For example: my_struct.my_sub_ident struct StructSubIdentExprModel { - Token: &lex::Token + Token: &token::Token Expr: &Data Method: &FnIns Field: &FieldIns @@ -220,7 +220,7 @@ struct BuiltinNewCallExprModel { // Expression Model: for built-in panic function calls. struct BuiltinPanicCallExprModel { - Token: &lex::Token + Token: &token::Token Expr: ExprModel } @@ -292,7 +292,7 @@ struct BackendEmitExprModel { } // Expression Model: for free calls. -// Function provided by: std::mem +// Function provided by: "std/mem" struct FreeExprModel { Expr: ExprModel } \ No newline at end of file diff --git a/std/jule/sema/package.jule b/std/jule/sema/package.jule index a2d29cbac..b23fe2eb2 100644 --- a/std/jule/sema/package.jule +++ b/std/jule/sema/package.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex -use strings for std::strings +use "std/fs/path" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" +use "std/strings" // Importer. // Used by semantic analyzer for import use declarations. @@ -148,23 +148,20 @@ fn defByIdentPackage(mut &files: []&SymTab, &ident: str, binded: bool): any { // Import information. // Represents imported package by use declaration. struct ImportInfo { - // Use declaration token. - Token: &lex::Token + // Declaration. + Decl: &ast::UseDecl // Absolute path. Path: str // Use declaration path string. + // Quotes are not included. LinkPath: str - // Package identifier (aka package name). - // Empty if package is cpp header. - Ident: str - // Package alias identifier. Alias: str - // True if imported with Importer.get_import function. + // True if imported with Importer.GetImport function. Duplicate: bool // Is binded use declaration. @@ -173,12 +170,6 @@ struct ImportInfo { // Is standard library package. Std: bool - // Is imported all defines implicitly. - ImportAll: bool - - // Identifiers of selected definition. - Selected: []&lex::Token - // Nil if package is cpp header. Package: &Package @@ -196,7 +187,7 @@ impl Lookup for ImportInfo { // Lookups by import way such as identifier selection. // Just lookups non-binded defines. fn FindVar(mut self, ident: str, _: bool): &Var { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findVarInPackage(self.Package.Files, ident, false) @@ -208,7 +199,7 @@ impl Lookup for ImportInfo { // Lookups by import way such as identifier selection. // Just lookups non-binded defines. fn FindTypeAlias(mut self, ident: str, _: bool): &TypeAlias { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findTypeAliasInPackage(self.Package.Files, ident, false) @@ -220,7 +211,7 @@ impl Lookup for ImportInfo { // Lookups by import way such as identifier selection. // Just lookups non-binded defines. fn FindStruct(mut self, ident: str, _: bool): &Struct { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findStructInPackage(self.Package.Files, ident, false) @@ -232,7 +223,7 @@ impl Lookup for ImportInfo { // Lookups by import way such as identifier selection. // Just lookups non-binded defines. fn FindFn(mut self, ident: str, _: bool): &Fn { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findFnInPackage(self.Package.Files, ident, false) @@ -243,7 +234,7 @@ impl Lookup for ImportInfo { // // Lookups by import way such as identifier selection. fn FindTrait(mut self, ident: str): &Trait { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findTraitInPackage(self.Package.Files, ident) @@ -254,7 +245,7 @@ impl Lookup for ImportInfo { // // Lookups by import way such as identifier selection. fn FindEnum(mut self, ident: str): &Enum { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findEnumInPackage(self.Package.Files, ident) @@ -265,7 +256,7 @@ impl Lookup for ImportInfo { // // Lookups by import way such as identifier selection. fn FindTypeEnum(mut self, ident: str): &TypeEnum { - if !self.isLookupable(ident) { + if !self.isLookupable() { ret nil } ret findTypeEnumInPackage(self.Package.Files, ident) @@ -273,39 +264,12 @@ impl Lookup for ImportInfo { } impl ImportInfo { - fn isLookupable(self, &ident: str): bool { + fn isLookupable(self): bool { if self.Binded { ret false } - - if !self.ImportAll { - if len(self.Alias) != 0 || self.existIdent(lex::TokenKind.Self) { - ret true - } - - if len(self.Selected) > 0 { - if !self.existIdent(ident) { - ret false - } - } - } ret true } - - // Reports whether identifier is selected. - fn existIdent(self, ident: str): bool { - for _, sident in self.Selected { - if sident.Kind == ident { - ret true - } - } - - ret false - } - - fn isAccessibleViaSelection(self): bool { - ret self.ImportAll || len(self.Selected) == 0 || self.existIdent(lex::TokenKind.Self) - } } // Package. diff --git a/std/jule/sema/pattern.jule b/std/jule/sema/pattern.jule index 17abd0929..0b9fd3611 100644 --- a/std/jule/sema/pattern.jule +++ b/std/jule/sema/pattern.jule @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Pattern checker for functions and methods. -struct FuncPattern {} +struct FuncPattern{} impl FuncPattern { // Reports whether function is the reserved Dispose function. diff --git a/std/jule/sema/runtime.jule b/std/jule/sema/runtime.jule index 497110224..a927b26a1 100644 --- a/std/jule/sema/runtime.jule +++ b/std/jule/sema/runtime.jule @@ -11,7 +11,7 @@ fn runtimeFindFn(mut &runtime: &ImportInfo, ident: runtimeFunc): &Fn { const Binded = false mut f := runtime.FindFn(ident, Binded) if f == nil { - panic("runtime function is not exist, this is an implementation mistake, this panic call should be unreachable") + panic("sema: runtime function is not exist, this is an implementation mistake, this panic call should be unreachable") } ret f } @@ -24,7 +24,7 @@ fn runtimeFindStruct(mut &runtime: &ImportInfo, ident: runtimeStruct): &Struct { const Binded = false mut f := runtime.FindStruct(ident, Binded) if f == nil { - panic("runtime struct is not exist, this is an implementation mistake, this panic call should be unreachable") + panic("sema: runtime struct is not exist, this is an implementation mistake, this panic call should be unreachable") } ret f } \ No newline at end of file diff --git a/std/jule/sema/scope.jule b/std/jule/sema/scope.jule index b06a6a4d2..5c60fb34b 100644 --- a/std/jule/sema/scope.jule +++ b/std/jule/sema/scope.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use constant for std::jule::constant -use lex for std::jule::lex -use types for std::jule::types +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/token" +use "std/jule/types" // Statement type. enum Stmt: type { @@ -94,13 +94,13 @@ fn getExprModels(mut &m: ast::ExprData): []ast::ExprData { } } -fn checkMut(mut &s: &sema, &left: &Data, mut right: &Data, op: &lex::Token): (ok: bool) { +fn checkMut(mut &s: &sema, &left: &Data, mut right: &Data, op: &token::Token): (ok: bool) { match { | !left.Mutable: s.pushErr(op, build::LogMsg.AssignToNonMut) ret false | right != nil && !right.Mutable && right.Kind.Mutable(): - if op.Id != lex::TokenId.Eq && right.Kind.Struct() != nil { + if op.Id != token::Id.Eq && right.Kind.Struct() != nil { // If operator is not assignment, and kind is structure, allow. // Operator overloading uses immutable copy of right operand. // It's safe. @@ -113,7 +113,7 @@ fn checkMut(mut &s: &sema, &left: &Data, mut right: &Data, op: &lex::Token): (ok } } -fn checkAssign(mut &s: &sema, mut &left: &Data, mut right: &Data, op: &lex::Token): (ok: bool) { +fn checkAssign(mut &s: &sema, mut &left: &Data, mut right: &Data, op: &token::Token): (ok: bool) { f := left.Kind.Fn() if f != nil && f.Decl != nil && f.Decl.Global { s.pushErr(op, build::LogMsg.AssignTypeNotSupportValue) @@ -246,7 +246,7 @@ struct Label { // Goto statement. struct GotoSt { Ident: str - Token: &lex::Token + Token: &token::Token Label: &Label Scope: &Scope // Owner scope. Index: int // Index of statement. @@ -262,7 +262,7 @@ struct Postfix { struct Assign { Left: &OperandExprModel Right: &OperandExprModel - Op: &lex::Token + Op: &token::Token } // Multi-declarative assignment. @@ -314,14 +314,14 @@ struct RetSt { } struct scopeLabel { - token: &lex::Token + token: &token::Token node: &Label used: bool } // Scope checker. struct scopeChecker { - calledFrom: &lex::Token + calledFrom: &token::Token s: &sema owner: &FnIns // See developer reference (1). parent: &scopeChecker @@ -609,7 +609,7 @@ impl scopeChecker { if v.Scope == nil { // Ignore globals. ret false } - ret v.Scope == self.scope || !self.s.isFlag(SemaFlag.Shadowing) + ret v.Scope == self.scope || !self.s.isFlag(Flag.Shadowing) } ta := self.FindTypeAlias(ident, false) @@ -617,7 +617,7 @@ impl scopeChecker { if ta.Scope == nil { // Ignore globals. ret false } - ret ta.Scope == self.tree || !self.s.isFlag(SemaFlag.Shadowing) + ret ta.Scope == self.tree || !self.s.isFlag(Flag.Shadowing) } ret false @@ -704,7 +704,7 @@ impl scopeChecker { self.scope.Stmts = append(self.scope.Stmts, s) } - fn processErrorCall(mut &self, mut &m: &BuiltinErrorCallExprModel, err: &lex::Token) { + fn processErrorCall(mut &self, mut &m: &BuiltinErrorCallExprModel, err: &token::Token) { if self.isDeferred() { self.s.pushErr(err, build::LogMsg.ErrorInDeferred) } @@ -863,13 +863,13 @@ impl scopeChecker { fn checkComptimeRangeIter(mut &self, mut &it: &ast::Iter, mut &kind: &RangeIter, mut &d: &Data) { if kind.KeyA != nil { - if !self.s.isFlag(SemaFlag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyA.Ident) { + if !self.s.isFlag(Flag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyA.Ident) { self.s.pushErr(kind.KeyA.Token, build::LogMsg.DuplicatedIdent, kind.KeyA.Ident) self.s.pushSuggestion(build::LogMsg.RenameForAvoidDuplication) } } if kind.KeyB != nil { - if !self.s.isFlag(SemaFlag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyB.Ident) { + if !self.s.isFlag(Flag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyB.Ident) { self.s.pushErr(kind.KeyB.Token, build::LogMsg.DuplicatedIdent, kind.KeyB.Ident) self.s.pushSuggestion(build::LogMsg.RenameForAvoidDuplication) } @@ -957,7 +957,7 @@ impl scopeChecker { mut scope := self.getChild() if kind.KeyA != nil { - if !self.s.isFlag(SemaFlag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyA.Ident) { + if !self.s.isFlag(Flag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyA.Ident) { self.s.pushErr(kind.KeyA.Token, build::LogMsg.DuplicatedIdent, kind.KeyA.Ident) self.s.pushSuggestion(build::LogMsg.RenameForAvoidDuplication) } @@ -966,7 +966,7 @@ impl scopeChecker { } if kind.KeyB != nil { - if !self.s.isFlag(SemaFlag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyB.Ident) { + if !self.s.isFlag(Flag.Shadowing) && self.isDuplicatedIdent(0, kind.KeyB.Ident) { self.s.pushErr(kind.KeyB.Token, build::LogMsg.DuplicatedIdent, kind.KeyB.Ident) self.s.pushSuggestion(build::LogMsg.RenameForAvoidDuplication) } @@ -1176,7 +1176,7 @@ impl scopeChecker { } fn isNewAssignIdent(mut self, ident: str): bool { - if lex::IsIgnoreIdent(ident) || ident == "" { + if token::IsIgnoreIdent(ident) || ident == "" { ret false } ret self.table.defByIdent(ident, false) == nil @@ -1207,25 +1207,25 @@ impl scopeChecker { // Should follow this method. let mut overload: &FnIns = nil match a.Setter.Id { - | lex::TokenId.PlusEq: + | token::Id.PlusEq: overload = s.Operators.AddAssign - | lex::TokenId.MinusEq: + | token::Id.MinusEq: overload = s.Operators.SubAssign - | lex::TokenId.SolidusEq: + | token::Id.SolidusEq: overload = s.Operators.DivAssign - | lex::TokenId.StarEq: + | token::Id.StarEq: overload = s.Operators.MulAssign - | lex::TokenId.PercentEq: + | token::Id.PercentEq: overload = s.Operators.ModAssign - | lex::TokenId.ShlEq: + | token::Id.ShlEq: overload = s.Operators.ShlAssign - | lex::TokenId.ShrEq: + | token::Id.ShrEq: overload = s.Operators.ShrAssign - | lex::TokenId.VlineEq: + | token::Id.VlineEq: overload = s.Operators.BitOrAssign - | lex::TokenId.AmperEq: + | token::Id.AmperEq: overload = s.Operators.BitAndAssign - | lex::TokenId.CaretEq: + | token::Id.CaretEq: overload = s.Operators.BitXorAssign |: self.s.pushErr(a.Setter, build::LogMsg.OperatorNotForJuleType, a.Setter.Kind, s.Str()) @@ -1244,7 +1244,7 @@ impl scopeChecker { fn checkSingleAssign(mut &self, mut &a: &ast::AssignSt) { let mut l: &Data = nil - if !lex::IsIgnoreIdent(a.Left[0].Ident) { + if !token::IsIgnoreIdent(a.Left[0].Ident) { mut expr := a.Left[0].Expr l = self.s.eval(self).evalExpr(expr) if l == nil { @@ -1270,7 +1270,7 @@ impl scopeChecker { if r.Kind.Void() { self.s.pushErr(a.Right.Token, build::LogMsg.InvalidExpr) } - if a.Setter.Id != lex::TokenId.Eq { + if a.Setter.Id != token::Id.Eq { self.s.pushErr(a.Setter, build::LogMsg.InvalidSyntax) } self.scope.Stmts = append(self.scope.Stmts, r) @@ -1296,7 +1296,7 @@ impl scopeChecker { } self.scope.Stmts = append(self.scope.Stmts, &Assign{Left: lm, Right: rm, Op: a.Setter}) - if a.Setter.Id == lex::TokenId.Eq { + if a.Setter.Id == token::Id.Eq { mut checker := assignTypeChecker{ s: self.s, dest: l.Kind, @@ -1325,7 +1325,7 @@ impl scopeChecker { fn processEndPartOfMultiAssign(mut &self, mut &st: &MultiAssign, mut &a: &ast::AssignSt, mut &lexpr: &ast::AssignLeft, mut &l: &Data, mut &r: &Data, strict: bool) { - if !lexpr.Reference && lex::IsIgnoreIdent(lexpr.Ident) { + if !lexpr.Reference && token::IsIgnoreIdent(lexpr.Ident) { if r.Kind.Void() { self.s.pushErr(a.Right.Token, build::LogMsg.InvalidExpr) } @@ -1351,7 +1351,7 @@ impl scopeChecker { self.stop() ret } - if lex::IsIgnoreIdent(lexpr.Ident) { + if token::IsIgnoreIdent(lexpr.Ident) { self.s.pushErr(lexpr.Token, build::LogMsg.IgnoreIdent) } @@ -1400,7 +1400,7 @@ impl scopeChecker { } fn checkMultiAssign(mut &self, mut &a: &ast::AssignSt) { - if a.Setter.Id != lex::TokenId.Eq && a.Setter.Id != lex::TokenId.ColonEq { + if a.Setter.Id != token::Id.Eq && a.Setter.Id != token::Id.ColonEq { self.s.pushErr(a.Setter, build::LogMsg.InvalidSyntax) ret } @@ -1439,7 +1439,7 @@ impl scopeChecker { for i in a.Left { mut lexpr := a.Left[i] let mut l: &Data = nil - if !lex::IsIgnoreIdent(lexpr.Ident) { + if !token::IsIgnoreIdent(lexpr.Ident) { if !a.Declarative { goto eval } @@ -1468,7 +1468,7 @@ impl scopeChecker { fn checkAssignSt(mut &self, mut a: &ast::AssignSt) { match { - | lex::IsPostfixOp(a.Setter.Id): + | token::IsPostfixOp(a.Setter.Id): self.checkPostfix(a) | len(a.Left) == 1: self.checkSingleAssign(a) @@ -1589,7 +1589,7 @@ impl scopeChecker { ret def } - fn checkComptimePanic(mut &self, mut callToken: &lex::Token, &s: &Scope) { + fn checkComptimePanic(mut &self, mut callToken: &token::Token, &s: &Scope) { if len(s.Stmts) != 1 { ret } @@ -1624,7 +1624,7 @@ impl scopeChecker { fn processConstMatch(mut &self, mut &tm: &Match, mut &m: &ast::MatchCase) { for (i, mut c) in tm.Cases { if c.Scope != nil { - let mut token: &lex::Token = nil + let mut token: &token::Token = nil if !tm.TypeMatch && len(c.Scope.Stmts) > 0 { token = m.Cases[i].Scope.Stmts[0].Token } @@ -1638,7 +1638,7 @@ impl scopeChecker { tm.Cases = nil tm.Default = self.checkDefault(tm, m.Default) if tm.Default != nil { - let mut token: &lex::Token = nil + let mut token: &token::Token = nil if !tm.TypeMatch { token = m.Default.Scope.Stmts[0].Token } @@ -2089,7 +2089,7 @@ impl scopeChecker { fn checkVars(mut self) { for _, v in self.table.Vars { - if !v.Used && !v.Constant && !lex::IsIgnoreIdent(v.Ident) && !lex::IsAnonIdent(v.Ident) { + if !v.Used && !v.Constant && !token::IsIgnoreIdent(v.Ident) && !token::IsAnonIdent(v.Ident) { self.s.pushErr(v.Token, build::LogMsg.DeclaredButNotUsed, v.Ident) } } @@ -2097,7 +2097,7 @@ impl scopeChecker { fn checkAliases(mut self) { for _, a in self.table.TypeAliases { - if !a.Used && !lex::IsIgnoreIdent(a.Ident) && !lex::IsAnonIdent(a.Ident) { + if !a.Used && !token::IsIgnoreIdent(a.Ident) && !token::IsAnonIdent(a.Ident) { self.s.pushErr(a.Token, build::LogMsg.DeclaredButNotUsed, a.Ident) } } @@ -2137,28 +2137,28 @@ impl scopeChecker { } } -fn removeEqFromOp(op: lex::TokenId): lex::TokenId { +fn removeEqFromOp(op: token::Id): token::Id { match op { - | lex::TokenId.PlusEq: - ret lex::TokenId.Plus - | lex::TokenId.MinusEq: - ret lex::TokenId.Minus - | lex::TokenId.StarEq: - ret lex::TokenId.Star - | lex::TokenId.SolidusEq: - ret lex::TokenId.Solidus - | lex::TokenId.PercentEq: - ret lex::TokenId.Percent - | lex::TokenId.ShlEq: - ret lex::TokenId.Shl - | lex::TokenId.ShrEq: - ret lex::TokenId.Shr - | lex::TokenId.CaretEq: - ret lex::TokenId.Caret - | lex::TokenId.AmperEq: - ret lex::TokenId.Amper - | lex::TokenId.VlineEq: - ret lex::TokenId.Vline + | token::Id.PlusEq: + ret token::Id.Plus + | token::Id.MinusEq: + ret token::Id.Minus + | token::Id.StarEq: + ret token::Id.Star + | token::Id.SolidusEq: + ret token::Id.Solidus + | token::Id.PercentEq: + ret token::Id.Percent + | token::Id.ShlEq: + ret token::Id.Shl + | token::Id.ShrEq: + ret token::Id.Shr + | token::Id.CaretEq: + ret token::Id.Caret + | token::Id.AmperEq: + ret token::Id.Amper + | token::Id.VlineEq: + ret token::Id.Vline |: ret op } diff --git a/std/jule/sema/sema.jule b/std/jule/sema/sema.jule index 3e0eefbcb..8919fdb8d 100644 --- a/std/jule/sema/sema.jule +++ b/std/jule/sema/sema.jule @@ -2,13 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use build for std::jule::build -use constant for std::jule::constant -use lex for std::jule::lex -use mod for std::jule::internal::mod -use types for std::jule::types -use strings for std::strings +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/internal/mod" +use "std/jule/token" +use "std/jule/types" +use "std/strings" +use "std/unicode/utf8" fn isValidModelForRef(mut &m: ExprModel): bool { match type m { @@ -19,7 +20,7 @@ fn isValidModelForRef(mut &m: ExprModel): bool { ret model.Field != nil && isValidModelForRef(model.Expr.Model) | &UnaryExprModel: mut unary := (&UnaryExprModel)(m) - if unary.Op.Id != lex::TokenId.Star { + if unary.Op.Id != token::Id.Star { ret false } // Return true because of raw pointer dereferencing is an Unsafe Jule feature. @@ -44,7 +45,7 @@ fn isValidModelForRef(mut &m: ExprModel): bool { } } -fn compilerErr(&token: &lex::Token, line: bool, fmt: build::LogMsg, args: ...any): build::Log { +fn compilerErr(&token: &token::Token, line: bool, fmt: build::LogMsg, args: ...any): build::Log { mut log := build::Log{ Kind: build::LogKind.Error, Row: token.Row, @@ -58,18 +59,6 @@ fn compilerErr(&token: &lex::Token, line: bool, fmt: build::LogMsg, args: ...any ret log } -fn impIsLookupable(&i: &ImportInfo, &ident: str): bool { - if i.Binded { - ret false - } - if !i.ImportAll { - if len(i.Selected) > 0 { - ret i.existIdent(ident) - } - } - ret i.ImportAll -} - fn appendRetVars(mut &dest: []&Var, mut &f: &FnIns) { if f.Decl.IsVoid() || f.Result == nil { ret @@ -77,7 +66,7 @@ fn appendRetVars(mut &dest: []&Var, mut &f: &FnIns) { mut types := f.Types() for (i, mut ident) in f.Decl.Result.Idents { - if lex::IsIgnoreIdent(ident.Kind) || lex::IsAnonIdent(ident.Kind) { + if token::IsIgnoreIdent(ident.Kind) || token::IsAnonIdent(ident.Kind) { continue } dest = append(dest, &Var{ @@ -106,7 +95,7 @@ fn appendParamVars(mut &dest: []&Var, mut &f: &FnIns) { } for (_, mut p) in f.Params { - if lex::IsIgnoreIdent(p.Decl.Ident) || lex::IsAnonIdent(p.Decl.Ident) { + if token::IsIgnoreIdent(p.Decl.Ident) || token::IsAnonIdent(p.Decl.Ident) { continue } @@ -201,7 +190,7 @@ fn appendGenericTypeAliases(mut &dest: []&TypeAlias, mut &f: &FnIns) { } } -fn findFile(mut &files: []&SymTab, &handler: &lex::File): &SymTab { +fn findFile(mut &files: []&SymTab, &handler: &token::Fileset): &SymTab { for (_, mut fl) in files { if fl.File == handler { ret fl @@ -216,7 +205,7 @@ unsafe fn pushSuggestion(mut log: *build::Log, fmt: build::LogMsg, args: ...any) struct commonSemaMeta { comptimeTypeInfos: []&comptimeTypeInfo - runtime: &ImportInfo // Implicitly imported [std::runtime] package. + runtime: &ImportInfo // Implicitly imported "std/runtime" package. } impl commonSemaMeta { @@ -238,7 +227,7 @@ struct sema { errors: []build::Log files: []&SymTab // Package files. file: &SymTab // Current package file. - flags: SemaFlag + flags: Flag meta: &commonSemaMeta } @@ -265,23 +254,6 @@ impl Lookup for sema { if v != nil { ret v } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - v = imp.FindVar(ident, binded) - if v != nil && self.isAccessibleDefine(v.Public, v.Token) { - ret v - } - } - ret nil } @@ -297,23 +269,6 @@ impl Lookup for sema { if ta != nil { ret ta } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - ta = imp.FindTypeAlias(ident, binded) - if ta != nil && self.isAccessibleDefine(ta.Public, ta.Token) { - ret ta - } - } - ret nil } @@ -329,22 +284,6 @@ impl Lookup for sema { if s != nil { ret s } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - s = imp.FindStruct(ident, binded) - if s != nil && self.isAccessibleDefine(s.Public, s.Token) { - ret s - } - } ret nil } @@ -360,23 +299,6 @@ impl Lookup for sema { if f != nil { ret f } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - f = imp.FindFn(ident, binded) - if f != nil && self.isAccessibleDefine(f.Public, f.Token) { - ret f - } - } - ret nil } @@ -392,23 +314,6 @@ impl Lookup for sema { if t != nil { ret t } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - t = imp.FindTrait(ident) - if t != nil && self.isAccessibleDefine(t.Public, t.Token) { - ret t - } - } - ret nil } @@ -424,23 +329,6 @@ impl Lookup for sema { if e != nil { ret e } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - e = imp.FindEnum(ident) - if e != nil && self.isAccessibleDefine(e.Public, e.Token) { - ret e - } - } - ret nil } @@ -456,35 +344,18 @@ impl Lookup for sema { if e != nil { ret e } - - // If identifier is not public, it should be built-in or package define. - if !mod::IsPub(ident) { - ret nil - } - - // Lookup current file's public denifes of imported packages. - for (_, mut imp) in self.file.Imports { - if !impIsLookupable(imp, ident) { - continue - } - e = imp.FindTypeEnum(ident) - if e != nil && self.isAccessibleDefine(e.Public, e.Token) { - ret e - } - } - ret nil } } impl sema { // Reports whether flags has given flag. - fn isFlag(self, flags: SemaFlag): bool { ret self.flags&flags == flags } + fn isFlag(self, flags: Flag): bool { ret self.flags&flags == flags } fn getCurrentFile(mut self): &SymTab { ret self.file } fn setCurrentFile(mut self, mut f: &SymTab) { self.file = f } - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.errors = append(self.errors, compilerErr(token, true, fmt, args...)) } @@ -495,7 +366,7 @@ impl sema { // Reports whether define is accessible in the current package. // The public and token parameters belongs to define which is accessed. - fn isAccessibleDefine(self, public: bool, token: &lex::Token): bool { + fn isAccessibleDefine(self, public: bool, token: &token::Token): bool { if public || token.File == nil { // defins is public or built-in ret true @@ -507,7 +378,7 @@ impl sema { ret true } // define is not public or in-package define - // but it may come from the std::runtime package + // but it may come from the runtime package // so allow access if standard library package tries if isStdPackage(tokenDir, "runtime") && isStdPackage(selfDir, "") { ret true @@ -523,14 +394,6 @@ impl sema { if f.isDuplicatedIdent(itself, ident, binded) { ret true } - - for _, imp in f.Imports { - for _, selected in imp.Selected { - if selected.Kind == ident { - ret true - } - } - } } ret false } @@ -544,7 +407,7 @@ impl sema { dc.check() } - fn checkGenericQuantity(mut self, required: int, given: int, token: &lex::Token): (ok: bool) { + fn checkGenericQuantity(mut self, required: int, given: int, token: &token::Token): (ok: bool) { match { | required == 0 && given > 0: self.pushErr(token, build::LogMsg.NotHasGenerics) @@ -563,19 +426,6 @@ impl sema { } } - fn isDuplicatedImportSelection(self, itself: uintptr, &ident: str): bool { - for _, imp in self.file.Imports { - if uintptr(imp) == itself { - // Don't scan trailing imports. - break - } - if imp.existIdent(ident) { - ret true - } - } - ret false - } - fn getImportDef(self, &ident: str, mut &imp: &ImportInfo): any { if findPackageBuiltinDef(imp.LinkPath, ident) != nil { ret true @@ -591,7 +441,7 @@ impl sema { ret nil } - fn checkImportSelection[T](mut self, &ident: &lex::Token, &s: T): bool { + fn checkImportSelection[T](mut self, &ident: &token::Token, &s: T): bool { if !self.isAccessibleDefine(s.Public, s.Token) { self.pushErr(ident, build::LogMsg.IdentIsNotAccessible, ident.Kind) self.pushSuggestion(build::LogMsg.MakePubToAccess) @@ -605,56 +455,7 @@ impl sema { ret true } - fn checkImportSelectedSelections(mut self, mut &imp: &ImportInfo): (ok: bool) { - ok = true - for _, ident in imp.Selected { - if ident.Kind == lex::TokenKind.Self { - continue - } - - if self.isDuplicatedImportSelection(uintptr(imp), ident.Kind) { - self.pushErr(ident, build::LogMsg.DuplicatedIdent, ident.Kind) - self.pushSuggestion(build::LogMsg.RenameForAvoidDuplication) - ok = false - continue - } - - mut def := self.getImportDef(ident.Kind, imp) - match type def { - | bool: - // Pass, built-in. - continue - | &Var: - mut v := (&Var)(def) - ok = self.checkImportSelection(ident, v) && ok - | &TypeAlias: - mut ta := (&TypeAlias)(def) - ok = self.checkImportSelection(ident, ta) && ok - | &Struct: - mut s := (&Struct)(def) - ok = self.checkImportSelection(ident, s) && ok - | &Trait: - mut t := (&Trait)(def) - ok = self.checkImportSelection(ident, t) && ok - | &Enum: - mut e := (&Enum)(def) - ok = self.checkImportSelection(ident, e) && ok - | &TypeEnum: - mut e := (&TypeEnum)(def) - ok = self.checkImportSelection(ident, e) && ok - | &Fn: - mut f := (&Fn)(def) - ok = self.checkImportSelection(ident, f) && ok - |: - self.pushErr(ident, build::LogMsg.IdentNotExist, ident.Kind) - ok = false - continue - } - } - ret - } - - fn checkImportsAllSelectionsFromCollection[T](mut self, &s: []T, &et: &lex::Token): bool { + fn checkImportsAllSelectionsFromCollection[T](mut self, &s: []T, &et: &token::Token): bool { mut ok := true for _, d in s { if d.Public { @@ -664,29 +465,6 @@ impl sema { ret ok } - fn checkImportAllSelections(mut self, &imp: &ImportInfo): (ok: bool) { - ok = true - for _, file in imp.Package.Files { - ok = self.checkImportsAllSelectionsFromCollection(file.Vars, imp.Token) && ok - ok = self.checkImportsAllSelectionsFromCollection(file.TypeAliases, imp.Token) && ok - ok = self.checkImportsAllSelectionsFromCollection(file.Structs, imp.Token) && ok - ok = self.checkImportsAllSelectionsFromCollection(file.Funcs, imp.Token) && ok - ok = self.checkImportsAllSelectionsFromCollection(file.Traits, imp.Token) && ok - ok = self.checkImportsAllSelectionsFromCollection(file.Enums, imp.Token) && ok - ok = self.checkImportsAllSelectionsFromCollection(file.TypeEnums, imp.Token) && ok - } - ret - } - - fn checkImportSelections(mut self, mut &imp: &ImportInfo): (ok: bool) { - if len(imp.Selected) > 0 { - ret self.checkImportSelectedSelections(imp) - } else if imp.ImportAll { - ret self.checkImportAllSelections(imp) - } - ret true - } - fn isUseAliasDuplication(mut self, &imp: &ImportInfo): bool { for (_, mut imp2) in self.file.Imports { if imp2 == imp { @@ -695,34 +473,52 @@ impl sema { if imp2.Alias == imp.Alias { ret true } - // Catch identifiers of other use declarations. - if imp2.Ident == imp2.LinkPath && imp2.Ident == imp.Alias { - ret true - } } ret false } - fn checkImport(mut self, mut &imp: &ImportInfo): bool { - if imp.Binded || len(imp.Package.Files) == 0 { + fn checkAutoAlias(mut self, mut &imp: &ImportInfo): bool { + if imp.LinkPath == "std/unsafe" { + // the "std/unsafe" package is able to use unsafe keyword as alias ret true } - - // Check special cases for std::unsafe. - if imp.LinkPath == "std::unsafe" { - if imp.ImportAll || imp.Alias != "" || len(imp.Selected) > 0 { - self.pushErr(imp.Token, build::LogMsg.ExpectedPlainUseDecl, "use std::unsafe") - ret false + valid := isValidImpAlias(imp.Alias) + if valid { + if self.isUseAliasDuplication(imp) { + self.pushErr(imp.Decl.Path, build::LogMsg.DuplicatedUseAlias, imp.Alias) + self.pushSuggestion(build::LogMsg.GiveAnAliasManually, imp.Decl.Path.Kind) } + } else { + self.pushErr(imp.Decl.Path, build::LogMsg.AutoAliasFail, imp.Decl.Path.Kind) + self.pushSuggestion(build::LogMsg.GiveAnAliasManually, imp.Decl.Path.Kind) } + ret valid + } - if len(imp.Alias) != 0 { - if lex::IsIgnoreIdent(imp.Alias) { - self.pushErr(imp.Token, build::LogMsg.IgnoreIdent) + fn checkImport(mut self, mut &imp: &ImportInfo): bool { + if imp.Binded { + ret true + } + + if imp.Decl.Alias != nil { // custom alias found + if token::IsIgnoreIdent(imp.Alias) { + self.pushErr(imp.Decl.Token, build::LogMsg.IgnoreIdent) } else if self.isUseAliasDuplication(imp) { - self.pushErr(imp.Token, build::LogMsg.DuplicatedUseAlias, imp.Alias) + self.pushErr(imp.Decl.Token, build::LogMsg.DuplicatedUseAlias, imp.Alias) self.pushSuggestion(build::LogMsg.RenameUseAliasAvoidDuplication) } + + // Check special cases for the "std/unsafe" package. + if imp.LinkPath == "std/unsafe" { + self.pushErr(imp.Decl.Alias, build::LogMsg.ExpectedPlainUseDecl, `use "std/unsafe"`) + ret false + } + } else if !self.checkAutoAlias(imp) { + ret false + } + + if len(imp.Package.Files) == 0 { + ret true } if !imp.Duplicate { @@ -737,7 +533,7 @@ impl sema { ret false } } - ret self.checkImportSelections(imp) + ret true } fn checkImports(mut self) { @@ -913,7 +709,7 @@ impl sema { } fn checkAssignType(mut &self, destIsRef: bool, mut &dest: &TypeKind, - mut &d: &Data, mut errorToken: &lex::Token, mut refers: &ReferenceStack): bool { + mut &d: &Data, mut errorToken: &token::Token, mut refers: &ReferenceStack): bool { if d.Decl { self.pushErr(errorToken, build::LogMsg.InvalidExpr) ret false @@ -956,7 +752,7 @@ impl sema { } fn _checkTypeCompatibility(mut &self, mut &dest: &TypeKind, mut &src: &TypeKind, - mut errorToken: &lex::Token): bool { + mut errorToken: &token::Token): bool { if src == nil { ret false } @@ -974,7 +770,7 @@ impl sema { } fn checkTypeCompatibility(mut &self, mut &dest: &TypeKind, - mut &src: &TypeKind, mut &errorToken: &lex::Token): bool { + mut &src: &TypeKind, mut &errorToken: &token::Token): bool { if self._checkTypeCompatibility(dest, src, errorToken) { ret true } @@ -983,7 +779,7 @@ impl sema { } fn pushCompatiblityError(mut self, mut &dest: &TypeKind, mut &src: &Data, - mut &errorToken: &lex::Token) { + mut &errorToken: &token::Token) { if src.untyped { match { | src.Constant.IsI64(): @@ -1001,7 +797,7 @@ impl sema { } fn checkTypeCompatibility1(mut &self, mut &dest: &TypeKind, mut &src: &Data, - mut &errorToken: &lex::Token): bool { + mut &errorToken: &token::Token): bool { if self._checkTypeCompatibility(dest, src.Kind, errorToken) { ret true } @@ -1079,7 +875,7 @@ impl sema { ret ins } - fn checkConstraintsFn(mut &self, mut &f: &FnIns, mut &et: &lex::Token, mut exist: &FnIns): bool { + fn checkConstraintsFn(mut &self, mut &f: &FnIns, mut &et: &token::Token, mut exist: &FnIns): bool { mut cc := self.constraintChecker() cc.et = et cc.fi = f @@ -1093,7 +889,7 @@ impl sema { ret cc.check() } - fn checkConstraintsStruct(mut &self, mut &s: &StructIns, mut &et: &lex::Token, mut exist: &StructIns): bool { + fn checkConstraintsStruct(mut &self, mut &s: &StructIns, mut &et: &token::Token, mut exist: &StructIns): bool { mut cc := self.constraintChecker() cc.et = et cc.si = s @@ -1189,7 +985,7 @@ impl sema { }) } - fn checkRefValidityForInitExpr(mut &self, leftMut: bool, mut &d: &Data, mut &errorToken: &lex::Token): bool { + fn checkRefValidityForInitExpr(mut &self, leftMut: bool, mut &d: &Data, mut &errorToken: &token::Token): bool { if !isValidModelForRef(d.Model) { self.pushErr(errorToken, build::LogMsg.RefAssignNonVar) ret false @@ -1234,7 +1030,7 @@ impl sema { } fn checkValidityForInitExpr(mut &self, leftMut: bool, leftRef: bool, - &leftKind: &TypeKind, mut &d: &Data, mut &errorToken: &lex::Token): bool { + &leftKind: &TypeKind, mut &d: &Data, mut &errorToken: &token::Token): bool { if leftMut && !d.Mutable { // Check classical assignment mutability. if d.Kind.Mutable() || d.Kind.Variadic { @@ -1285,7 +1081,7 @@ impl sema { } fn checkTypeAliasDecl(mut &self, mut &ta: &TypeAlias, mut l: Lookup) { - if lex::IsIgnoreIdent(ta.Ident) { + if token::IsIgnoreIdent(ta.Ident) { self.pushErr(ta.Token, build::LogMsg.IgnoreIdent) } self.checkTypeAliasDeclKind(ta, l) @@ -1293,7 +1089,7 @@ impl sema { // Checks type alias declaration with duplicated identifiers. fn checkTypeAliasDeclDup(mut &self, mut &ta: &TypeAlias) { - if lex::IsIgnoreIdent(ta.Ident) { + if token::IsIgnoreIdent(ta.Ident) { self.pushErr(ta.Token, build::LogMsg.IgnoreIdent) } if self.isDuplicatedIdent(uintptr(ta), ta.Ident, ta.Binded) { @@ -1320,7 +1116,7 @@ impl sema { for _, item in items { if item.Ident == "" { continue - } else if lex::IsIgnoreIdent(item.Ident) { + } else if token::IsIgnoreIdent(item.Ident) { self.pushErr(item.Token, build::LogMsg.IgnoreIdent) } else { for _, citem in items { @@ -1374,7 +1170,7 @@ impl sema { | u64: item.Value.Data.Constant = constant::Const.NewU64(n) |: - panic("unimplemented enum int type, this panic call should be unreachable") + panic("sema: unimplemented enum int type, this panic call should be unreachable") } item.Value.Data.Model = item.Value.Data.Constant } else { @@ -1394,7 +1190,7 @@ impl sema { | u64: n = item.Value.Data.Constant.ReadU64() |: - panic("unimplemented enum int type, this panic call should be unreachable") + panic("sema: unimplemented enum int type, this panic call should be unreachable") } } } @@ -1407,7 +1203,7 @@ impl sema { | u64: max = types::MaxU(prim.Str()) |: - panic("unimplemented enum int type, this panic call should be unrechable") + panic("sema: unimplemented enum int type, this panic call should be unrechable") } mut eval := self.eval(self) @@ -1421,7 +1217,7 @@ impl sema { | u64: n = first.Value.Data.Constant.AsU64() |: - panic("unimplemented enum int type, this panic call should be unreachable") + panic("sema: unimplemented enum int type, this panic call should be unreachable") } } for (_, mut item) in e.Items[1:] { @@ -1445,7 +1241,7 @@ impl sema { } fn checkEnumDecl(mut &self, mut &e: &Enum) { - if lex::IsIgnoreIdent(e.Ident) { + if token::IsIgnoreIdent(e.Ident) { self.pushErr(e.Token, build::LogMsg.IgnoreIdent) } else if self.isDuplicatedIdent(uintptr(e), e.Ident, false) { self.pushErr(e.Token, build::LogMsg.DuplicatedIdent, e.Ident) @@ -1465,7 +1261,7 @@ impl sema { } } else { // Set to default type. - e.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + e.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } mut t := e.Kind.Kind.Prim() @@ -1486,7 +1282,7 @@ impl sema { } fn checkTypeEnumDecl(mut &self, mut &e: &TypeEnum) { - if lex::IsIgnoreIdent(e.Ident) { + if token::IsIgnoreIdent(e.Ident) { self.pushErr(e.Token, build::LogMsg.IgnoreIdent) } else if self.isDuplicatedIdent(uintptr(e), e.Ident, false) { self.pushErr(e.Token, build::LogMsg.DuplicatedIdent, e.Ident) @@ -1551,7 +1347,7 @@ impl sema { fn checkDeclGenerics(mut self, &generics: []&ast::GenericDecl): (ok: bool) { ok = true for i, g in generics { - if lex::IsIgnoreIdent(g.Ident) { + if token::IsIgnoreIdent(g.Ident) { self.pushErr(g.Token, build::LogMsg.IgnoreIdent) ok = false continue @@ -1595,10 +1391,10 @@ impl sema { | j >= i: // Skip current and following parameters. break paramsLookup - | lex::IsIgnoreIdent(p.Ident) - | lex::IsIgnoreIdent(jp.Ident) - | lex::IsAnonIdent(p.Ident) - | lex::IsAnonIdent(jp.Ident): + | token::IsIgnoreIdent(p.Ident) + | token::IsIgnoreIdent(jp.Ident) + | token::IsAnonIdent(p.Ident) + | token::IsAnonIdent(jp.Ident): // Skip anonymous parameters. break paramsLookup | p.Ident == jp.Ident: @@ -1620,7 +1416,7 @@ impl sema { // Check duplications. for i, v in f.Result.Idents { - if lex::IsIgnoreIdent(v.Kind) || lex::IsAnonIdent(v.Kind) { + if token::IsIgnoreIdent(v.Kind) || token::IsAnonIdent(v.Kind) { continue // Skip anonymous return variables. } // Lookup in generics. @@ -1692,7 +1488,7 @@ impl sema { } } - fn catchTraitInheritCycle(mut &self, t1: &Trait, mut t2: &Trait, mut &message: strings::StrBuilder): (ok: bool) { + fn catchTraitInheritCycle(mut &self, t1: &Trait, mut t2: &Trait, mut &message: strings::Builder): (ok: bool) { ok = true for (_, mut i) in t2.Inherits { if i.Kind == nil { @@ -1738,7 +1534,7 @@ impl sema { self.pushErr(it.Decl.Token, build::LogMsg.IllegalCycleRefersItself, t.Ident) ok = false } else { - mut message := strings::StrBuilder.New(1 << 6) + mut message := strings::Builder.New(1 << 6) ok = ok && self.catchTraitInheritCycle(t, t2, message) if message.Len() > 0 { mut errMsg := message.Str() @@ -1778,9 +1574,9 @@ impl sema { } fn checkTraitDeclMethod(mut &self, mut &f: &Fn) { - if lex::IsIgnoreIdent(f.Ident) { + if token::IsIgnoreIdent(f.Ident) { self.pushErr(f.Token, build::LogMsg.IgnoreIdent) - } else if lex::IsAnonIdent(f.Ident) { + } else if token::IsAnonIdent(f.Ident) { self.pushErr(f.Token, build::LogMsg.AnonFn) } f.sema = self @@ -1828,7 +1624,7 @@ impl sema { } fn checkTraitDecl(mut &self, mut &t: &Trait) { - if lex::IsIgnoreIdent(t.Ident) { + if token::IsIgnoreIdent(t.Ident) { self.pushErr(t.Token, build::LogMsg.IgnoreIdent) } else if self.isDuplicatedIdent(uintptr(t), t.Ident, false) { self.pushErr(t.Token, build::LogMsg.DuplicatedIdent, t.Ident) @@ -1983,7 +1779,7 @@ impl sema { // Checks variable declaration. // Will not check duplicated identifiers. fn checkVarDecl(mut &self, mut &decl: &Var, mut l: Lookup) { - if lex::IsIgnoreIdent(decl.Ident) { + if token::IsIgnoreIdent(decl.Ident) { self.pushErr(decl.Token, build::LogMsg.IgnoreIdent) } @@ -2108,7 +1904,7 @@ impl sema { } fn checkStructDecl(mut &self, mut &s: &Struct) { - if lex::IsIgnoreIdent(s.Ident) { + if token::IsIgnoreIdent(s.Ident) { self.pushErr(s.Token, build::LogMsg.IgnoreIdent) } else if self.isDuplicatedIdent(uintptr(s), s.Ident, s.Binded) { self.pushErr(s.Token, build::LogMsg.DuplicatedIdent, s.Ident) @@ -2143,7 +1939,7 @@ impl sema { } fn checkFuncDecl(mut &self, mut &f: &Fn) { - if lex::IsIgnoreIdent(f.Ident) { + if token::IsIgnoreIdent(f.Ident) { self.pushErr(f.Token, build::LogMsg.IgnoreIdent) } else if f.IsAnon() { self.pushErr(f.Token, build::LogMsg.AnonFn) @@ -2180,7 +1976,7 @@ impl sema { ret self.checkFuncDeclsBy(self.file.Funcs) } - fn pushCycleError(self, &st1: str, &st2: str, mut &message: strings::StrBuilder) { + fn pushCycleError(self, &st1: str, &st2: str, mut &message: strings::Builder) { const Padding = 7 refersTo := build::Logf(build::LogMsg.RefersTo, st1, st2) m := message.Str() @@ -2190,7 +1986,7 @@ impl sema { message.WriteStr(m) } - fn checkCrossCycle(self, &st1: &Struct, &st2: &Struct, mut &message: strings::StrBuilder): bool { + fn checkCrossCycle(self, &st1: &Struct, &st2: &Struct, mut &message: strings::Builder): bool { for _, u in st2.Uses { if u == st1 { self.pushCycleError(st2.Ident, u.Ident, message) @@ -2240,14 +2036,14 @@ impl sema { } } - fn checkDataForTypeInference(mut self, &d: &Data, &err_token: &lex::Token) { + fn checkDataForTypeInference(mut self, &d: &Data, &errToken: &token::Token) { match { | d.IsNil(): - self.pushErr(err_token, build::LogMsg.NilForTypeInference) + self.pushErr(errToken, build::LogMsg.NilForTypeInference) | d.IsVoid(): - self.pushErr(err_token, build::LogMsg.VoidForTypeInference) + self.pushErr(errToken, build::LogMsg.VoidForTypeInference) | d.Kind.Variadic: - self.pushErr(err_token, build::LogMsg.InvalidExprForTypeInference) + self.pushErr(errToken, build::LogMsg.InvalidExprForTypeInference) } } @@ -2362,7 +2158,7 @@ impl sema { // Checks new generics function instance. // If instance is already exist, f will point to exist instantantiation. - fn checkGenericFn(mut &self, mut &f: &FnIns, mut &et: &lex::Token): (ok: bool, exist: bool) { + fn checkGenericFn(mut &self, mut &f: &FnIns, mut &et: &token::Token): (ok: bool, exist: bool) { ok = self.reloadFnInsTypes(f) f.reloaded = true if !ok { @@ -2408,7 +2204,7 @@ impl sema { // Checks environment-dependent parts of structure instance. // Which is contains fields and generic-type constraints. // If generic instance will be check, errorToken should be passed. - fn checkStructEnv(mut &self, mut &s: &StructIns, mut errorToken: &lex::Token): (ok: bool) { + fn checkStructEnv(mut &self, mut &s: &StructIns, mut errorToken: &token::Token): (ok: bool) { mut tc := typeChecker{ s: s.Decl.sema, rootLookup: s.Decl.sema, @@ -2505,7 +2301,7 @@ impl sema { ret } - fn precheckStructIns(mut &self, mut &s: &StructIns, mut errorToken: &lex::Token): (ok: bool) { + fn precheckStructIns(mut &self, mut &s: &StructIns, mut errorToken: &token::Token): (ok: bool) { ok = self.checkStructEnv(s, errorToken) if !ok { ret false @@ -2526,7 +2322,7 @@ impl sema { f.Generics = append(f.Generics, &InsGeneric{Kind: arr.Elem}) ok, _ = self.checkGenericFn(f, field.Decl.Token) if !ok { - panic("arrayCmp evaluation failed, this is an implementation mistake") + panic("sema: arrayCmp evaluation failed, this is an implementation mistake") } s.Refers.Push(f) } @@ -2686,7 +2482,7 @@ impl sema { } } - fn checkFnInsCaller(mut &self, mut &f: &FnIns, mut caller: &lex::Token) { + fn checkFnInsCaller(mut &self, mut &f: &FnIns, mut caller: &token::Token) { if f.Decl.Binded { ret } @@ -3038,7 +2834,7 @@ push: } } -fn pushRuntimeToStr(mut &s: &sema, mut &t: &TypeKind, mut &token: &lex::Token, +fn pushRuntimeToStr(mut &s: &sema, mut &t: &TypeKind, mut &token: &token::Token, mut refers: &ReferenceStack) { if s.meta.runtime == nil || t.IsNil() { ret @@ -3052,4 +2848,30 @@ fn pushRuntimeToStr(mut &s: &sema, mut &t: &TypeKind, mut &token: &lex::Token, if refers != nil { refers.Push(f) } +} + +// Reports whether the alias valid for the import alias. +// Designed to check auto aliases. +fn isValidImpAlias(mut alias: str): (valid: bool) { + if token::IsIgnoreIdent(alias) { + ret false + } + if token::IsKeyword(alias) { + ret false + } + mut r, mut size := utf8::DecodeRuneStr(alias) + if r != '_' && !token::IsLetter(r) { + ret false + } + for { + alias = alias[size:] + if len(alias) == 0 { + break + } + r, size = utf8::DecodeRuneStr(alias) + if r != '_' && !('0' <= r && r <= '9') && !token::IsLetter(r) { + ret false + } + } + ret true } \ No newline at end of file diff --git a/std/jule/sema/struct.jule b/std/jule/sema/struct.jule index 3c680b32a..66c4ebde1 100644 --- a/std/jule/sema/struct.jule +++ b/std/jule/sema/struct.jule @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use lex for std::jule::lex -use strings for std::internal::strings +use "std/internal/strings" +use "std/jule/ast" +use "std/jule/token" // Field. struct Field { Owner: &Struct - Token: &lex::Token + Token: &token::Token Public: bool Mutable: bool // Interior mutability. Ident: str @@ -73,7 +73,7 @@ struct Struct { // Stores all referred structures. Uses: []&Struct - Token: &lex::Token + Token: &token::Token Ident: str Fields: []&Field Methods: []&Fn @@ -238,7 +238,7 @@ impl Kind for StructIns { // Implement: Kind // Returns Struct's type kind as string. fn Str(self): str { - mut kind := strings::StrBuilder.New(1 << 5) + mut kind := strings::Builder.New(1 << 5) kind.WriteStr(self.Decl.Ident) if len(self.Generics) > 0 { kind.WriteByte('[') diff --git a/std/jule/sema/symbol.jule b/std/jule/sema/sym.jule similarity index 74% rename from std/jule/sema/symbol.jule rename to std/jule/sema/sym.jule index 797fe2fa9..90738b692 100644 --- a/std/jule/sema/symbol.jule +++ b/std/jule/sema/sym.jule @@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use fs for std::fs -use path for std::fs::path -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex -use strings for std::strings +use "std/fs" +use "std/fs/path" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" +use "std/strings" +use "std/unicode" +use "std/unicode/utf8" // Stack for symbol references. // It used by Sema to store necessary references. @@ -59,7 +61,7 @@ impl ReferenceStack { // Directive pass. struct Pass { - Token: &lex::Token + Token: &token::Token Text: str } @@ -301,11 +303,11 @@ impl symBuilder { ret root } - fn pushErr(mut self, &token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, &token: &token::Token, fmt: build::LogMsg, args: ...any) { self.errors = append(self.errors, compilerErr(token, true, fmt, args...)) } - fn pushErrText(mut self, &token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErrText(mut self, &token: &token::Token, fmt: build::LogMsg, args: ...any) { self.errors = append(self.errors, compilerErr(token, false, fmt, args...)) } @@ -323,11 +325,11 @@ impl symBuilder { // Exist? info := fs::Status.Of(path) else { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) + self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.Path.Kind) ret false } if info.IsDir() { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) + self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.Path.Kind) ret false } @@ -335,10 +337,10 @@ impl symBuilder { } fn buildCppHeaderImport(mut self, mut &decl: &ast::UseDecl): &ImportInfo { - mut path := decl.LinkPath + mut path := decl.Path.Kind[1:len(decl.Path.Kind)-1] // remove quotes - if !build::IsStdHeaderPath(decl.LinkPath) { - path = path::Join(decl.Token.File.Dir(), decl.LinkPath) + if !build::IsStdHeaderPath(path) { + path = path::Join(decl.Token.File.Dir(), path) mut ok := self.checkCppUseDeclPath(decl, path) if !ok { ret nil @@ -347,124 +349,137 @@ impl symBuilder { // Set to absolute path for correct include path. path, ok = path::Abs(path) if !ok { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) + self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.Path.Kind) } } ret &ImportInfo{ - Token: decl.Token, + Decl: decl, Path: path, - LinkPath: decl.LinkPath, - Ident: "", // Cpp headers haven't identifiers. + LinkPath: decl.Path.Kind, Binded: true, Std: false, Package: nil, // Cpp headers haven't symbol table. } } - fn buildStdImport(mut self, mut &decl: &ast::UseDecl): &ImportInfo { - // No need to check blank identifiers for standart packages. - mut path := decl.LinkPath[len("std::"):] // Skip "std::" prefix. - path = strings::Replace(path, lex::TokenKind.DblColon, str(path::Separator), -1) - path = path::Join(build::PathStdlib, path) - path, ok := path::Abs(path) + // Checks and returns absolute path of import filepath. + // Designed for non-std package paths. + // Returns empty string if error occurs. + fn checkAbsPath(mut &self, mut filepath: str, mut &decl: &ast::UseDecl): str { + modPath := self.importer.GetModPath() + if len(modPath) == 0 { + self.pushErr(decl.Path, build::LogMsg.ModuleNotFound) + self.pushSuggestion(build::LogMsg.UseModInit) + ret "" + } + + filepath = path::Join(modPath, filepath) + filepath, ok := path::Abs(filepath) if !ok { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) - ret nil + self.pushErr(decl.Path, build::LogMsg.UseNotFound, decl.Path.Kind) + ret "" } // Exist? - info := fs::Status.Of(path) else { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) - ret nil + info := fs::Status.Of(filepath) else { + self.pushErr(decl.Path, build::LogMsg.UseNotFound, decl.Path.Kind) + ret "" } if !info.IsDir() { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) - ret nil + self.pushErr(decl.Path, build::LogMsg.UseNotFound, decl.Path.Kind) + ret "" } - // Select last identifier of namespace chain. - i := strings::FindLast(decl.LinkPath, lex::TokenKind.DblColon) + 1 - ident := decl.LinkPath[i:] - - ret &ImportInfo{ - ImportAll: decl.Full, - Token: decl.Token, // Use decl token for correct implementation. See developer refernece (9). - Path: path, - LinkPath: decl.LinkPath, - Ident: ident, - Alias: decl.Alias, - Binded: false, - Std: true, - Package: &Package{ - Files: nil, // Appends by import algorithm. - }, - } + ret filepath } - fn buildIdentImport(mut &self, mut &decl: &ast::UseDecl): &ImportInfo { - if decl.LinkPath == "_" || - strings::Find(decl.LinkPath, "::_::") != -1 || - strings::HasSuffix(decl.LinkPath, "::_") { - self.pushErr(decl.Token, build::LogMsg.BlankIdentInUseDecl) - ret nil + // Same as the [checkAbsPath] method but designed for std package paths. + fn checkStdAbsPath(mut &self, mut filepath: str, mut &decl: &ast::UseDecl): str { + filepath = filepath[len("std")+1:] // cut "std" + pathsep prefix + filepath = path::Join(build::PathStdlib, filepath) + filepath, ok := path::Abs(filepath) + if !ok { + self.pushErr(decl.Path, build::LogMsg.UseNotFound, decl.Path.Kind) + ret "" } - modPath := self.importer.GetModPath() - if len(modPath) == 0 { - self.pushErr(decl.Token, build::LogMsg.ModuleNotFound) - self.pushSuggestion(build::LogMsg.UseModInit) - ret nil + // Exist? + info := fs::Status.Of(filepath) else { + self.pushErr(decl.Path, build::LogMsg.UseNotFound, decl.Path.Kind) + ret "" + } + if !info.IsDir() { + self.pushErr(decl.Path, build::LogMsg.UseNotFound, decl.Path.Kind) + ret "" } - mut path := decl.LinkPath - path = strings::Replace(path, lex::TokenKind.DblColon, str(path::Separator), -1) - path = path::Join(modPath, path) + ret filepath + } - path, ok := path::Abs(path) - if !ok { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) - ret nil + // Checks import path and returns as filepath if no error exist. + fn checkImpPath(mut &self, mut &decl: &ast::UseDecl): (std: bool, filepath: str) { + path := decl.Path.Kind[1:len(decl.Path.Kind)-1] // remove quotes + if strings::HasSuffix(path, build::ImportPathSep) { + self.pushErr(decl.Path, build::LogMsg.InvalidImportPath, decl.Path.Kind) + ret + } + parts := strings::Split(path, build::ImportPathSep, -1) + if len(parts) == 0 { + self.pushErr(decl.Path, build::LogMsg.InvalidImportPath, decl.Path.Kind) + ret + } + std = parts[0] == "std" + for _, part in parts { + if part == "" || token::IsIgnoreIdent(part) { + self.pushErr(decl.Path, build::LogMsg.InvalidImportPath, decl.Path.Kind) + ret false, "" + } + filepath = path::Join(filepath, part) } - // Exist? - info := fs::Status.Of(path) else { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) - ret nil + // build absolute path + if std { + filepath = self.checkStdAbsPath(filepath, decl) + } else { + filepath = self.checkAbsPath(filepath, decl) } - if !info.IsDir() { - self.pushErr(decl.Token, build::LogMsg.UseNotFound, decl.LinkPath) + ret + } + + // Assigns an alias to import. + fn assignAlias(mut &self, mut &imp: &ImportInfo) { + mut i := strings::FindLast(imp.LinkPath, build::ImportPathSep) + i++ // skip separator and also if -1 it takes full path + path := imp.LinkPath[i:] + imp.Alias = path + } + + fn buildImport(mut &self, mut &decl: &ast::UseDecl): &ImportInfo { + if decl.Binded { + ret self.buildCppHeaderImport(decl) + } + std, filepath := self.checkImpPath(decl) + if filepath == "" { // error occured ret nil } - // Select last identifier of namespace chain. - i := strings::FindLast(decl.LinkPath, lex::TokenKind.DblColon) + 1 - ident := decl.LinkPath[i:] - - ret &ImportInfo{ - ImportAll: decl.Full, - Token: decl.Token, - Path: path, - LinkPath: decl.LinkPath, - Ident: ident, - Alias: decl.Alias, + mut imp := &ImportInfo{ + Decl: decl, + Path: filepath, + LinkPath: decl.Path.Kind[1:len(decl.Path.Kind)-1], Binded: false, - Std: false, + Std: std, Package: &Package{ Files: nil, // Appends by import algorithm. }, } - } - - fn buildImport(mut &self, mut &decl: &ast::UseDecl): &ImportInfo { - match { - | decl.Binded: - ret self.buildCppHeaderImport(decl) - | decl.Std: - ret self.buildStdImport(decl) - |: - ret self.buildIdentImport(decl) + if decl.Alias != nil { + imp.Alias = decl.Alias.Kind + } else { + self.assignAlias(imp) } + ret imp } fn findUseDecl(mut self, &pkg: &ImportInfo): &ImportInfo { @@ -480,30 +495,19 @@ impl symBuilder { if lpkg == nil { ret true } - self.pushErr(pkg.Token, build::LogMsg.DuplicateUseDecl, pkg.LinkPath) + self.pushErr(pkg.Decl.Token, build::LogMsg.DuplicateUseDecl, pkg.LinkPath) self.pushSuggestion(build::LogMsg.RemoveUseDeclAvoidDuplication) ret false } - fn implImportSelections(mut self, mut &imp: &ImportInfo, mut &decl: &ast::UseDecl) { - imp.Selected = decl.Selected - for _, item in imp.Selected { - for _, citem in imp.Selected { - if item == citem { - break - } else if item.Kind == citem.Kind { - self.pushErr(item, build::LogMsg.DuplicatedUseSelection, item.Kind) - self.pushSuggestion(build::LogMsg.RemoveUseSelectionAvoidDupliation) - break - } - } - } - } - fn getAsLinkPath(mut &self, mut path: str): str { + mut sb := strings::Builder.New(len(path)) if strings::HasPrefix(path, build::PathStdlib) { - path = path[len(build::PathStdlib):] - ret "std" + strings::Replace(path, str(path::Separator), lex::TokenKind.DblColon, -1) + path = path[len(build::PathStdlib):] // cut absolute path prefix + sb.WriteStr(`"std`) + sb.WriteStr(strings::Replace(path, str(path::Separator), build::ImportPathSep, -1)) + sb.WriteByte('"') + ret sb.Str() } root, _ := path::Abs(self.importer.GetModPath()) @@ -511,10 +515,13 @@ impl symBuilder { if path[0] == path::Separator { path = path[1:] } - ret strings::Replace(path, str(path::Separator), lex::TokenKind.DblColon, -1) + sb.WriteByte('"') + sb.WriteStr(strings::Replace(path, str(path::Separator), build::ImportPathSep, -1)) + sb.WriteByte('"') + ret sb.Str() } - fn pushCycleError(mut &self, &sb: &symBuilder, path: str, mut &message: strings::StrBuilder) { + fn pushCycleError(mut &self, &sb: &symBuilder, path: str, mut &message: strings::Builder) { const Padding = 7 refersTo := build::Logf( build::LogMsg.RefersTo, @@ -527,8 +534,8 @@ impl symBuilder { message.WriteStr(m) } - fn pushCrossCycleError(mut &self, &target: &symBuilder, &imp: &ImportInfo, &errorToken: &lex::Token) { - mut message := strings::StrBuilder.New(1 << 5) + fn pushCrossCycleError(mut &self, &target: &symBuilder, &imp: &ImportInfo, &errorToken: &token::Token) { + mut message := strings::Builder.New(1 << 5) self.pushCycleError(self, imp.Path, message) @@ -582,8 +589,32 @@ impl symBuilder { // - mod: module that imports relevant package. // - path: path of package that importing. fn checkPackageAccessibility(mut self, &decl: &ast::UseDecl, &mod: str, &path: str) { - if self.importer.GetModPath() != mod && strings::Contains(path, "internal") { + if self.importer.GetModPath() == mod { + ret + } + const InternalName = "internal" + i := strings::Find(path, InternalName) + if i == -1 { + ret + } + if i == 0 { + // "internal" or "internal/" ? + if len(path)-len(InternalName) == 0 || + strings::HasPrefix(path, InternalName+build::ImportPathSep) { + self.pushErr(decl.Token, build::LogMsg.UseDeclForInternal) + } + ret + } + // "/internal" ? + if path[i-1:] == build::ImportPathSep+InternalName { self.pushErr(decl.Token, build::LogMsg.UseDeclForInternal) + ret + } + // "/internal/" ? + n := i + len(InternalName) + 1 + if n < len(path) && path[i-1:n] == build::ImportPathSep+InternalName+build::ImportPathSep { + self.pushErr(decl.Token, build::LogMsg.UseDeclForInternal) + ret } } @@ -630,7 +661,6 @@ impl symBuilder { imp.Package.Files = append(imp.Package.Files, table) } } - self.implImportSelections(imp, decl) ret true } @@ -709,7 +739,7 @@ impl symBuilder { } arg := d.Args[0] - if arg.Id != lex::TokenId.Lit { + if arg.Id != token::Id.Lit { self.pushErr(arg, build::LogMsg.InvalidSyntax) ret } @@ -758,5 +788,5 @@ impl symBuilder { // Reports whether imp is implicitly imported. // See developer reference (9). fn isImplicitImport(imp: &ImportInfo): bool { - ret imp.Token == nil + ret imp.Decl.Token == nil } \ No newline at end of file diff --git a/std/jule/sema/table.jule b/std/jule/sema/symtab.jule similarity index 90% rename from std/jule/sema/table.jule rename to std/jule/sema/symtab.jule index 38603c399..e8a6d929b 100644 --- a/std/jule/sema/table.jule +++ b/std/jule/sema/symtab.jule @@ -2,22 +2,22 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex +use "std/jule/token" // Symbol table. // Builds by semantic analyzer. struct SymTab { - File: &lex::File // Owner fileset of this symbol table. - Passes: []Pass // All passed flags with jule:pass directive. - Imports: []&ImportInfo // Imported packages. - Vars: []&Var // Variables. - TypeAliases: []&TypeAlias // Type aliases. - Structs: []&Struct // Structures. - Funcs: []&Fn // Functions. - Traits: []&Trait // Traits. - Enums: []&Enum // Enums. - TypeEnums: []&TypeEnum // Type enums. - Impls: []&Impl // Implementations. + File: &token::Fileset // Owner fileset of this symbol table. + Passes: []Pass // All passed flags with jule:pass directive. + Imports: []&ImportInfo // Imported packages. + Vars: []&Var // Variables. + TypeAliases: []&TypeAlias // Type aliases. + Structs: []&Struct // Structures. + Funcs: []&Fn // Functions. + Traits: []&Trait // Traits. + Enums: []&Enum // Enums. + TypeEnums: []&TypeEnum // Type enums. + Impls: []&Impl // Implementations. } impl Lookup for SymTab { diff --git a/std/jule/sema/trait.jule b/std/jule/sema/trait.jule index 51283a887..ed4906ef3 100644 --- a/std/jule/sema/trait.jule +++ b/std/jule/sema/trait.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use lex for std::jule::lex +use "std/jule/token" // Trait. struct Trait { - Token: &lex::Token + Token: &token::Token Ident: str Public: bool Inherits: []&TypeSymbol diff --git a/std/jule/sema/type.jule b/std/jule/sema/type.jule index b760c8f12..58b6bba09 100644 --- a/std/jule/sema/type.jule +++ b/std/jule/sema/type.jule @@ -5,14 +5,12 @@ // This file reserved for types, type kinds and type build algorithms. // This file haven't type compatibility checking algorithm or something else. -use conv for std::conv -use ast for std::jule::ast -use build for std::jule::build -use lex for std::jule::lex -use types for std::jule::types -use strings for std::strings - -type PrimKind: types::TypeKind +use "std/conv" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/token" +use "std/jule/types" +use "std/strings" // Generic type for instance types. struct InsGeneric { @@ -27,7 +25,7 @@ struct TypeAlias { Binded: bool Used: bool Generic: bool - Token: &lex::Token + Token: &token::Token Ident: str Kind: &TypeSymbol Refers: []any // Referred identifiers, except binded ones. @@ -55,7 +53,7 @@ impl Kind for TypeKind { ret "nil" } - mut kind := strings::StrBuilder.New(1 << 4) + mut kind := strings::Builder.New(1 << 4) if self.Variadic { kind.WriteStr("...") @@ -532,52 +530,52 @@ impl Prim { } // Reports whether type is primitive i8. - fn IsI8(self): bool { ret self.Kind == PrimKind.I8 } + fn IsI8(self): bool { ret self.Kind == types::Kind.I8 } // Reports whether type is primitive i16. - fn IsI16(self): bool { ret self.Kind == PrimKind.I16 } + fn IsI16(self): bool { ret self.Kind == types::Kind.I16 } // Reports whether type is primitive i32. - fn IsI32(self): bool { ret self.Kind == PrimKind.I32 } + fn IsI32(self): bool { ret self.Kind == types::Kind.I32 } // Reports whether type is primitive i64. - fn IsI64(self): bool { ret self.Kind == PrimKind.I64 } + fn IsI64(self): bool { ret self.Kind == types::Kind.I64 } // Reports whether type is primitive u8. - fn IsU8(self): bool { ret self.Kind == PrimKind.U8 } + fn IsU8(self): bool { ret self.Kind == types::Kind.U8 } // Reports whether type is primitive u16. - fn IsU16(self): bool { ret self.Kind == PrimKind.U16 } + fn IsU16(self): bool { ret self.Kind == types::Kind.U16 } // Reports whether type is primitive u32. - fn IsU32(self): bool { ret self.Kind == PrimKind.U32 } + fn IsU32(self): bool { ret self.Kind == types::Kind.U32 } // Reports whether type is primitive u64. - fn IsU64(self): bool { ret self.Kind == PrimKind.U64 } + fn IsU64(self): bool { ret self.Kind == types::Kind.U64 } // Reports whether type is primitive f32. - fn IsF32(self): bool { ret self.Kind == PrimKind.F32 } + fn IsF32(self): bool { ret self.Kind == types::Kind.F32 } // Reports whether type is primitive f64. - fn IsF64(self): bool { ret self.Kind == PrimKind.F64 } + fn IsF64(self): bool { ret self.Kind == types::Kind.F64 } // Reports whether type is primitive int. - fn IsInt(self): bool { ret self.Kind == PrimKind.Int } + fn IsInt(self): bool { ret self.Kind == types::Kind.Int } // Reports whether type is primitive uint. - fn IsUint(self): bool { ret self.Kind == PrimKind.Uint } + fn IsUint(self): bool { ret self.Kind == types::Kind.Uint } // Reports whether type is primitive uintptr. - fn IsUintptr(self): bool { ret self.Kind == PrimKind.Uintptr } + fn IsUintptr(self): bool { ret self.Kind == types::Kind.Uintptr } // Reports whether type is primitive bool. - fn IsBool(self): bool { ret self.Kind == PrimKind.Bool } + fn IsBool(self): bool { ret self.Kind == types::Kind.Bool } // Reports whether type is primitive str. - fn IsStr(self): bool { ret self.Kind == PrimKind.Str } + fn IsStr(self): bool { ret self.Kind == types::Kind.Str } // Reports whether type is primitive any. - fn IsAny(self): bool { ret self.Kind == PrimKind.Any } + fn IsAny(self): bool { ret self.Kind == types::Kind.Any } } // Smart pointer. @@ -626,7 +624,7 @@ struct Tuple { impl Kind for Tuple { // Returns tuple kind as string. fn Str(self): str { - mut s := strings::StrBuilder.New(1 << 4) + mut s := strings::Builder.New(1 << 4) s.WriteByte('(') s.WriteStr(self.Types[0].Str()) for _, t in self.Types[1:] { @@ -666,7 +664,7 @@ struct Map { impl Kind for Map { // Returns map kind as string. fn Str(self): str { - mut s := strings::StrBuilder.New(1 << 4) + mut s := strings::Builder.New(1 << 4) s.WriteStr("map[") s.WriteStr(self.Key.Str()) s.WriteByte(']') @@ -694,7 +692,7 @@ struct Arr { impl Kind for Arr { // Returns array kind as string. fn Str(self): str { - mut s := strings::StrBuilder.New(1 << 4) + mut s := strings::Builder.New(1 << 4) s.WriteByte('[') s.WriteStr(conv::Itoa(self.N)) s.WriteByte(']') @@ -777,7 +775,7 @@ struct typeChecker { // If this not nil, type dependencies will push into stack. refers: &ReferenceStack - errorToken: &lex::Token + errorToken: &token::Token // This identifiers ignored and // appends as primitive type. @@ -819,7 +817,7 @@ struct typeChecker { } impl typeChecker { - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.s.pushErr(token, fmt, args...) } @@ -852,7 +850,7 @@ impl typeChecker { } } - fn pushCycleError(self, def1: any, def2: any, mut &message: strings::StrBuilder) { + fn pushCycleError(self, def1: any, def2: any, mut &message: strings::Builder) { const Padding = 7 getIdent := fn(&def: any): str { match type def { @@ -874,7 +872,7 @@ impl typeChecker { message.WriteStr(m) } - fn checkCrossCycle(self, decl: any, mut &message: strings::StrBuilder): bool { + fn checkCrossCycle(self, decl: any, mut &message: strings::Builder): bool { match type decl { | &TypeAlias: ta := (&TypeAlias)(decl) @@ -931,7 +929,7 @@ impl typeChecker { ret false } - mut message := strings::StrBuilder.New(1 << 5) + mut message := strings::Builder.New(1 << 5) if !self.checkCrossCycle(decl, message) { mut errMsg := message.Str() @@ -1072,7 +1070,7 @@ impl typeChecker { ret t } - fn checkStructIns(mut self, mut &ins: &StructIns, mut &errorToken: &lex::Token): (ok: bool) { + fn checkStructIns(mut self, mut &ins: &StructIns, mut &errorToken: &token::Token): (ok: bool) { if ins.Checked { ret true } @@ -1154,7 +1152,7 @@ impl typeChecker { ret ins } - fn fromStructIns(mut self, mut &ins: &StructIns, mut token: &lex::Token): &StructIns { + fn fromStructIns(mut self, mut &ins: &StructIns, mut token: &token::Token): &StructIns { mut existInstance := ins.Decl.appendInstance(ins) if existInstance != nil { if !self.s.checkConstraintsStruct(ins, token, existInstance) { @@ -1419,7 +1417,7 @@ impl typeChecker { self.pushErr(decl.Elem.Token, build::LogMsg.ArraySizeIsNeg) ret nil } else { - max := types::MaxI(PrimKind.Int) + max := types::MaxI(types::Kind.Int) if types::BitSize != 64 && i64(n) > max { self.pushErr(decl.Size.Token, build::LogMsg.ArraySizeOverflow, constoa(size.Constant), conv::FmtInt(max, 10)) @@ -1539,25 +1537,20 @@ impl typeChecker { ret ins } - fn buildByNamespace(mut self, mut decl: &ast::NamespaceTypeDecl): Kind { - path := buildLinkPathByTokens(decl.Idents) + fn buildNamespace(mut self, mut ns: &ast::NamespaceTypeDecl): Kind { mut imp := self.lookup.SelectPackage(fn(imp: &ImportInfo): bool { - if len(decl.Idents) == 1 && imp.Alias == path { - ret true - } - ret imp.LinkPath == path && imp.isAccessibleViaSelection() + ret imp.Alias == ns.Namespace.Kind }) - selfIdent := str(lex::TokenKind.Self) - if imp == nil || !imp.isLookupable(selfIdent) { - self.pushErr(decl.Idents[0], build::LogMsg.NamespaceNotExist, path) + if imp == nil || !imp.isLookupable() { + self.pushErr(ns.Namespace, build::LogMsg.NamespaceNotExist, ns.Namespace.Kind) ret nil } self.disallowBuiltin() mut lookup := self.lookup self.lookup = imp - mut kind := self.checkDecl(decl.Kind) + mut kind := self.checkDecl(ns.Kind) self.lookup = lookup self.allowBuiltin() ret kind @@ -1620,7 +1613,7 @@ impl typeChecker { } | &ast::NamespaceTypeDecl: self.inscatch = true - mut t := self.buildByNamespace((&ast::NamespaceTypeDecl)(declKind)) + mut t := self.buildNamespace((&ast::NamespaceTypeDecl)(declKind)) if t != nil { kind = t } @@ -1675,7 +1668,7 @@ impl typeChecker { } } -struct identTypeLookup {} +struct identTypeLookup{} impl identTypeLookup { static fn prim(&ident: str, t: &Prim): bool { @@ -1776,25 +1769,6 @@ fn isBuiltinStrConvertable(mut &t: &TypeKind): bool { ret !t.Void() && t.Fn() == nil && t.Tup() == nil && !t.comptime() } -fn buildLinkPathByTokens(&tokens: []&lex::Token): str { - if len(tokens) == 1 && tokens[0].Id == lex::TokenId.Unsafe { - ret "std::unsafe" - } - mut n := 0 - for _, token in tokens { - n += len(token.Kind) - n += 2 - } - mut s := strings::StrBuilder.New(n) - for i, token in tokens { - s.WriteStr(token.Kind) - if len(tokens)-i > 1 { - s.WriteStr("::") - } - } - ret s.Str() -} - fn buildPrimType(kind: str): &Prim { ret &Prim{ Kind: kind, @@ -1824,7 +1798,7 @@ fn getStructFromKind(mut k: &TypeKind): &Struct { } fn applyImplicitCast(mut &s: &sema, mut &dest: &TypeKind, mut &d: &Data, - mut &token: &lex::Token, mut refers: &ReferenceStack) { + mut &token: &token::Token, mut refers: &ReferenceStack) { if d.Kind.IsNil() { ret } diff --git a/std/jule/sema/type2.jule b/std/jule/sema/type2.jule index 4c68df035..7332dc444 100644 --- a/std/jule/sema/type2.jule +++ b/std/jule/sema/type2.jule @@ -4,14 +4,14 @@ // This file reserved for type compatibility checking. -use conv for std::conv -use math for std::math -use ast for std::jule::ast -use build for std::jule::build -use lit for std::jule::constant::lit -use lex for std::jule::lex -use strings for std::internal::strings -use types for std::jule::types +use "std/conv" +use "std/internal/strings" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant/lit" +use "std/jule/token" +use "std/jule/types" +use "std/math" fn traitHasReferenceReceiver(&t: &Trait): bool { for _, f in t.Methods { @@ -30,7 +30,7 @@ fn traitHasReferenceReceiver(&t: &Trait): bool { fn floatAssignable(&kind: str, &d: &Data): bool { value := conv::FmtFloat(d.Constant.AsF64(), 'g', -1, 64) - ret types::CheckBitFloat(value, types::BitsizeOf(kind)) + ret types::CheckBitFloat(value, types::BitSizeOf(kind)) } fn sigAssignable(kind: str, &d: &Data): bool { @@ -58,7 +58,7 @@ fn sigAssignable(kind: str, &d: &Data): bool { fn unsigAssignable(kind: str, &d: &Data): bool { max := types::Max(kind) - if d.IsRune && kind == types::TypeKind.U8 { + if d.IsRune && kind == types::Kind.U8 { ret lit::IsAscii(rune(d.Constant.ReadI64())) } @@ -100,7 +100,7 @@ struct typeCompatibilityChecker { s: &sema // Used for error logging. dest: &TypeKind src: &TypeKind - errorToken: &lex::Token + errorToken: &token::Token } impl typeCompatibilityChecker { @@ -236,7 +236,7 @@ struct assignTypeChecker { s: &sema // Used for error logging and type checking. dest: &TypeKind d: &Data - errorToken: &lex::Token + errorToken: &token::Token refers: &ReferenceStack } @@ -336,7 +336,7 @@ struct dynamicTypeAnnotation { f: &FnIns p: &ParamIns a: &Data - errorToken: &lex::Token + errorToken: &token::Token k: *&TypeKind c: &ast::TypeDecl ignored: []&TypeKind // Ignored generics. @@ -656,7 +656,7 @@ impl dynamicTypeAnnotation { struct fnCallArgChecker { e: &eval args: []&ast::Expr - errorToken: &lex::Token + errorToken: &token::Token f: &FnIns dynamicAnnotation: bool argModels: []ExprModel @@ -664,7 +664,7 @@ struct fnCallArgChecker { } impl fnCallArgChecker { - fn pushErrToken(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErrToken(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.e.s.pushErr(token, fmt, args...) } @@ -699,7 +699,7 @@ impl fnCallArgChecker { |: log = build::LogMsg.MissingArgs } - mut err := strings::StrBuilder.New(1 << 5) + mut err := strings::Builder.New(1 << 5) err.WriteStr(self.f.Decl.Ident) err.WriteStr("\n want (") for i, p in params { @@ -713,7 +713,7 @@ impl fnCallArgChecker { ret false } - fn checkArg(mut self, mut &p: &ParamIns, mut &arg: &Data, mut &errorToken: &lex::Token): (ok: bool) { + fn checkArg(mut self, mut &p: &ParamIns, mut &arg: &Data, mut &errorToken: &token::Token): (ok: bool) { if self.dynamicAnnotation && parameterUsesGenerics(p, self.f.Decl.Generics) { // Accept as fail if parameter is variadic or expression is invalid. ok = !p.Decl.Variadic && isGoodValueToInfer(arg) @@ -921,13 +921,13 @@ fn checkMutRiskOfStructLit(mut &s: &sema, &m: &StructLitExprModel) { struct structLitChecker { e: &eval - errorToken: &lex::Token + errorToken: &token::Token s: &StructIns args: []&StructArgExprModel } impl structLitChecker { - fn pushErr(mut self, token: &lex::Token, fmt: build::LogMsg, args: ...any) { + fn pushErr(mut self, token: &token::Token, fmt: build::LogMsg, args: ...any) { self.e.pushErr(token, fmt, args...) } @@ -936,7 +936,7 @@ impl structLitChecker { self.e.pushSuggestion(fmt, args...) } - fn pushMatch(mut self, mut &f: &FieldIns, mut &d: &Data, mut &errorToken: &lex::Token) { + fn pushMatch(mut self, mut &f: &FieldIns, mut &d: &Data, mut &errorToken: &token::Token) { const Reference = false // If evaluated for the immutable memory, check as immutable. // But if field in scope of the interior mutability, check as mutable. @@ -1074,7 +1074,7 @@ impl structLitChecker { ret } - mut idents := strings::StrBuilder.New(1 << 5) + mut idents := strings::Builder.New(1 << 5) for diff > 0; diff-- { idents.WriteStr(", ") idents.WriteStr(self.s.Fields[n-diff].Decl.Ident) @@ -1100,11 +1100,11 @@ impl rangeChecker { } fn setSizeKey(mut self) { - if self.rang.KeyA == nil || lex::IsIgnoreIdent(self.rang.KeyA.Ident) { + if self.rang.KeyA == nil || token::IsIgnoreIdent(self.rang.KeyA.Ident) { ret } self.Kind.KeyA = self.buildVar(self.rang.KeyA) - self.Kind.KeyA.Kind = findBuiltinTypeAlias(PrimKind.Int).Kind + self.Kind.KeyA.Kind = findBuiltinTypeAlias(types::Kind.Int).Kind } // Check range expression validity. @@ -1128,7 +1128,7 @@ impl rangeChecker { fn checkSlice(mut self) { self.setSizeKey() - if self.rang.KeyB == nil || lex::IsIgnoreIdent(self.rang.KeyB.Ident) { + if self.rang.KeyB == nil || token::IsIgnoreIdent(self.rang.KeyB.Ident) { ret } @@ -1141,7 +1141,7 @@ impl rangeChecker { fn checkArray(mut self) { self.setSizeKey() - if self.rang.KeyB == nil || lex::IsIgnoreIdent(self.rang.KeyB.Ident) { + if self.rang.KeyB == nil || token::IsIgnoreIdent(self.rang.KeyB.Ident) { ret } @@ -1153,7 +1153,7 @@ impl rangeChecker { } fn checkMapKeyA(mut self) { - if self.rang.KeyA == nil || lex::IsIgnoreIdent(self.rang.KeyA.Ident) { + if self.rang.KeyA == nil || token::IsIgnoreIdent(self.rang.KeyA.Ident) { ret } @@ -1168,7 +1168,7 @@ impl rangeChecker { } fn checkMapKeyB(mut self) { - if self.rang.KeyB == nil || lex::IsIgnoreIdent(self.rang.KeyB.Ident) { + if self.rang.KeyB == nil || token::IsIgnoreIdent(self.rang.KeyB.Ident) { ret } @@ -1189,11 +1189,11 @@ impl rangeChecker { fn checkStr(mut self) { self.setSizeKey() - if self.rang.KeyB == nil || lex::IsIgnoreIdent(self.rang.KeyB.Ident) { + if self.rang.KeyB == nil || token::IsIgnoreIdent(self.rang.KeyB.Ident) { ret } self.Kind.KeyB = self.buildVar(self.rang.KeyB) - self.Kind.KeyB.Kind = findBuiltinTypeAlias(PrimKind.U8).Kind + self.Kind.KeyB.Kind = findBuiltinTypeAlias(types::Kind.U8).Kind } fn checkComptime(mut self) { @@ -1204,7 +1204,7 @@ impl rangeChecker { if self.rang.KeyB != nil && self.rang.KeyB.Mutable { self.sc.s.pushErr(self.rang.KeyB.Token, build::LogMsg.CannotBeMut, self.rang.KeyB.Ident) } - if self.rang.KeyB == nil || lex::IsIgnoreIdent(self.rang.KeyB.Ident) { + if self.rang.KeyB == nil || token::IsIgnoreIdent(self.rang.KeyB.Ident) { ret } self.Kind.KeyB = self.buildVar(self.rang.KeyB) @@ -1259,9 +1259,9 @@ impl rangeChecker { struct retTypeChecker { sc: &scopeChecker f: &FnIns - types: []&TypeKind // Return types. - exprs: []&ast::Expr // Return expressions. - errorToken: &lex::Token + types: []&TypeKind // Return types. + exprs: []&ast::Expr // Return expressions. + errorToken: &token::Token model: ExprModel } @@ -1356,14 +1356,14 @@ impl retTypeChecker { } ret true err: - mut wanted := strings::StrBuilder.New(1 << 5) + mut wanted := strings::Builder.New(1 << 5) for i, t in self.types { wanted.WriteStr(t.Str()) if len(self.types)-i > 1 { wanted.WriteStr(", ") } } - mut given := strings::StrBuilder.New(1 << 5) + mut given := strings::Builder.New(1 << 5) for i, t in tup.Types { given.WriteStr(t.Str()) if len(self.types)-i > 1 { diff --git a/std/jule/sema/var.jule b/std/jule/sema/var.jule index e0abbc9f0..9eb015abc 100644 --- a/std/jule/sema/var.jule +++ b/std/jule/sema/var.jule @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use ast for std::jule::ast -use lex for std::jule::lex +use "std/jule/ast" +use "std/jule/token" // Variable. struct Var { Scope: &Scope - Token: &lex::Token + Token: &token::Token Ident: str Binded: bool Constant: bool diff --git a/std/jule/lex/file.jule b/std/jule/token/fileset.jule similarity index 85% rename from std/jule/lex/file.jule rename to std/jule/token/fileset.jule index 99cfd8591..930dfbe9a 100644 --- a/std/jule/lex/file.jule +++ b/std/jule/token/fileset.jule @@ -2,16 +2,23 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use path for std::fs::path +use "std/fs/path" // Fileset for lexing. -struct File { +struct Fileset { Path: str Data: []byte Tokens: []&Token } -impl File { +impl Fileset { + // Returns new Fileset with path. + static fn New(path: str): &Fileset { + ret &Fileset{ + Path: path, + } + } + // Fill data. fn Fill(mut self, mut data: []byte) { self.Data = data @@ -50,11 +57,4 @@ impl File { } ret "" } -} - -// Returns new File points to Jule file. -fn NewFileSet(path: str): &File { - ret &File{ - Path: path, - } } \ No newline at end of file diff --git a/std/jule/lex/lex.jule b/std/jule/token/lex.jule similarity index 77% rename from std/jule/lex/lex.jule rename to std/jule/token/lex.jule index d4704b6e7..1c0b52a7a 100644 --- a/std/jule/lex/lex.jule +++ b/std/jule/token/lex.jule @@ -2,102 +2,102 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use build for std::jule::build -use strings for std::internal::strings -use utf8 for std::unicode::utf8 +use "std/internal/strings" +use "std/jule/build" +use "std/unicode/utf8" // Lexer mode. -enum LexMode { +enum Mode { Standard: 0 << 0, // Standard mode. Comment: 1 << 0, // Standard mode + comments. } struct kindPair { - kind: TokenKind - id: TokenId + kind: Kind + id: Id } static keywords: [...]kindPair = [ - {TokenKind.Const, TokenId.Const}, - {TokenKind.Ret, TokenId.Ret}, - {TokenKind.Type, TokenId.Type}, - {TokenKind.For, TokenId.For}, - {TokenKind.Break, TokenId.Break}, - {TokenKind.Cont, TokenId.Cont}, - {TokenKind.In, TokenId.In}, - {TokenKind.If, TokenId.If}, - {TokenKind.Else, TokenId.Else}, - {TokenKind.Use, TokenId.Use}, - {TokenKind.Goto, TokenId.Goto}, - {TokenKind.Enum, TokenId.Enum}, - {TokenKind.Struct, TokenId.Struct}, - {TokenKind.Co, TokenId.Co}, - {TokenKind.Match, TokenId.Match}, - {TokenKind.Self, TokenId.Self}, - {TokenKind.Trait, TokenId.Trait}, - {TokenKind.Impl, TokenId.Impl}, - {TokenKind.Cpp, TokenId.Cpp}, - {TokenKind.Fall, TokenId.Fall}, - {TokenKind.Fn, TokenId.Fn}, - {TokenKind.Let, TokenId.Let}, - {TokenKind.Unsafe, TokenId.Unsafe}, - {TokenKind.Mut, TokenId.Mut}, - {TokenKind.Defer, TokenId.Defer}, - {TokenKind.Static, TokenId.Static}, - {TokenKind.Error, TokenId.Error}, - {TokenKind.Map, TokenId.Map}, + {Kind.Const, Id.Const}, + {Kind.Ret, Id.Ret}, + {Kind.Type, Id.Type}, + {Kind.For, Id.For}, + {Kind.Break, Id.Break}, + {Kind.Cont, Id.Cont}, + {Kind.In, Id.In}, + {Kind.If, Id.If}, + {Kind.Else, Id.Else}, + {Kind.Use, Id.Use}, + {Kind.Goto, Id.Goto}, + {Kind.Enum, Id.Enum}, + {Kind.Struct, Id.Struct}, + {Kind.Co, Id.Co}, + {Kind.Match, Id.Match}, + {Kind.Self, Id.Self}, + {Kind.Trait, Id.Trait}, + {Kind.Impl, Id.Impl}, + {Kind.Cpp, Id.Cpp}, + {Kind.Fall, Id.Fall}, + {Kind.Fn, Id.Fn}, + {Kind.Let, Id.Let}, + {Kind.Unsafe, Id.Unsafe}, + {Kind.Mut, Id.Mut}, + {Kind.Defer, Id.Defer}, + {Kind.Static, Id.Static}, + {Kind.Error, Id.Error}, + {Kind.Map, Id.Map}, ] static basicOps: [...]kindPair = [ - {TokenKind.DblColon, TokenId.DblColon}, - {TokenKind.ColonEq, TokenId.ColonEq}, - {TokenKind.Colon, TokenId.Colon}, - {TokenKind.Semicolon, TokenId.Semicolon}, - {TokenKind.Comma, TokenId.Comma}, - {TokenKind.TripleDot, TokenId.TripleDot}, - {TokenKind.Dot, TokenId.Dot}, - {TokenKind.PlusEq, TokenId.PlusEq}, - {TokenKind.MinusEq, TokenId.MinusEq}, - {TokenKind.StarEq, TokenId.StarEq}, - {TokenKind.SolidusEq, TokenId.SolidusEq}, - {TokenKind.PercentEq, TokenId.PercentEq}, - {TokenKind.ShlEq, TokenId.ShlEq}, - {TokenKind.ShrEq, TokenId.ShrEq}, - {TokenKind.CaretEq, TokenId.CaretEq}, - {TokenKind.AmperEq, TokenId.AmperEq}, - {TokenKind.VlineEq, TokenId.VlineEq}, - {TokenKind.Eqs, TokenId.Eqs}, - {TokenKind.NotEq, TokenId.NotEq}, - {TokenKind.GtEq, TokenId.GtEq}, - {TokenKind.LtEq, TokenId.LtEq}, - {TokenKind.DblAmper, TokenId.DblAmper}, - {TokenKind.DblVline, TokenId.DblVline}, - {TokenKind.Shl, TokenId.Shl}, - {TokenKind.Shr, TokenId.Shr}, - {TokenKind.DblPlus, TokenId.DblPlus}, - {TokenKind.DblMinus, TokenId.DblMinus}, - {TokenKind.Plus, TokenId.Plus}, - {TokenKind.Minus, TokenId.Minus}, - {TokenKind.Star, TokenId.Star}, - {TokenKind.Solidus, TokenId.Solidus}, - {TokenKind.Percent, TokenId.Percent}, - {TokenKind.Amper, TokenId.Amper}, - {TokenKind.Vline, TokenId.Vline}, - {TokenKind.Caret, TokenId.Caret}, - {TokenKind.Excl, TokenId.Excl}, - {TokenKind.Lt, TokenId.Lt}, - {TokenKind.Gt, TokenId.Gt}, - {TokenKind.Eq, TokenId.Eq}, - {TokenKind.Hash, TokenId.Hash}, - {TokenKind.LBrace, TokenId.LBrace}, - {TokenKind.RBrace, TokenId.RBrace}, - {TokenKind.LBracket, TokenId.LBracket}, - {TokenKind.RBracket, TokenId.RBracket}, - {TokenKind.LParent, TokenId.LParent}, - {TokenKind.RParent, TokenId.RParent}, + {Kind.DblColon, Id.DblColon}, + {Kind.ColonEq, Id.ColonEq}, + {Kind.Colon, Id.Colon}, + {Kind.Semicolon, Id.Semicolon}, + {Kind.Comma, Id.Comma}, + {Kind.TripleDot, Id.TripleDot}, + {Kind.Dot, Id.Dot}, + {Kind.PlusEq, Id.PlusEq}, + {Kind.MinusEq, Id.MinusEq}, + {Kind.StarEq, Id.StarEq}, + {Kind.SolidusEq, Id.SolidusEq}, + {Kind.PercentEq, Id.PercentEq}, + {Kind.ShlEq, Id.ShlEq}, + {Kind.ShrEq, Id.ShrEq}, + {Kind.CaretEq, Id.CaretEq}, + {Kind.AmperEq, Id.AmperEq}, + {Kind.VlineEq, Id.VlineEq}, + {Kind.Eqs, Id.Eqs}, + {Kind.NotEq, Id.NotEq}, + {Kind.GtEq, Id.GtEq}, + {Kind.LtEq, Id.LtEq}, + {Kind.DblAmper, Id.DblAmper}, + {Kind.DblVline, Id.DblVline}, + {Kind.Shl, Id.Shl}, + {Kind.Shr, Id.Shr}, + {Kind.DblPlus, Id.DblPlus}, + {Kind.DblMinus, Id.DblMinus}, + {Kind.Plus, Id.Plus}, + {Kind.Minus, Id.Minus}, + {Kind.Star, Id.Star}, + {Kind.Solidus, Id.Solidus}, + {Kind.Percent, Id.Percent}, + {Kind.Amper, Id.Amper}, + {Kind.Vline, Id.Vline}, + {Kind.Caret, Id.Caret}, + {Kind.Excl, Id.Excl}, + {Kind.Lt, Id.Lt}, + {Kind.Gt, Id.Gt}, + {Kind.Eq, Id.Eq}, + {Kind.Hash, Id.Hash}, + {Kind.LBrace, Id.LBrace}, + {Kind.RBrace, Id.RBrace}, + {Kind.LBracket, Id.LBracket}, + {Kind.RBracket, Id.RBracket}, + {Kind.LParent, Id.LParent}, + {Kind.RParent, Id.RParent}, ] -fn makeErr(row: int, col: int, &f: &File, fmt: build::LogMsg, args: ...any): build::Log { +fn makeErr(row: int, col: int, &f: &Fileset, fmt: build::LogMsg, args: ...any): build::Log { ret build::Log{ Kind: build::LogKind.Error, Row: row, @@ -434,9 +434,9 @@ fn byteEscape(&txt: []byte): (seq: str) { } struct lex { - mode: LexMode + mode: Mode tokens: []&Token - file: &File + file: &Fileset pos: int column: int row: int @@ -460,7 +460,7 @@ impl lex { self.newLine() for self.pos < len(self.file.Data) { mut token := self.token() - if token.Id != TokenId.Na { + if token.Id != Id.NA { self.tokens = append(self.tokens, token) } } @@ -527,8 +527,8 @@ impl lex { break } } - if self.mode&LexMode.Comment == LexMode.Comment { - token.Id = TokenId.Comment + if self.mode&Mode.Comment == Mode.Comment { + token.Id = Id.Comment token.Kind = str(self.file.Data[start:self.pos]) } } @@ -550,8 +550,8 @@ impl lex { self.file.Data[self.pos+1] == '/' { self.column += 2 self.pos += 2 - if self.mode&LexMode.Comment == LexMode.Comment { - token.Id = TokenId.Comment + if self.mode&Mode.Comment == Mode.Comment { + token.Id = Id.Comment token.Kind = str(self.file.Data[start:self.pos]) } ret @@ -623,7 +623,7 @@ impl lex { } fn lexRune(mut self, &txt: []byte): str { - mut run := strings::StrBuilder.New(1 << 3) + mut run := strings::Builder.New(1 << 3) run.WriteByte('\'') self.column++ mut n := 0 @@ -663,7 +663,7 @@ impl lex { } fn lexStr(mut self): str { - mut s := strings::StrBuilder.New(1 << 4) + mut s := strings::Builder.New(1 << 4) mark := self.file.Data[self.pos] self.pos++ // Skip mark raw := mark == '`' @@ -704,7 +704,7 @@ impl lex { self.column = 1 } - fn isOp(mut self, &txt: []byte, kind: str, id: TokenId, mut &t: &Token): bool { + fn isOp(mut self, &txt: []byte, kind: str, id: Id, mut &t: &Token): bool { if !bytesHasPrefix(txt, kind) { ret false } @@ -729,7 +729,7 @@ impl lex { ret false } t.Kind = lex - t.Id = TokenId.Ident + t.Id = Id.Ident ret true } @@ -739,7 +739,7 @@ impl lex { ret false } t.Kind = lex - t.Id = TokenId.Lit + t.Id = Id.Lit ret true } @@ -747,7 +747,7 @@ impl lex { fn token(mut self): &Token { mut t := &Token{ File: self.file, - Id: TokenId.Na, + Id: Id.NA, } txt := self.resume() @@ -766,16 +766,16 @@ impl lex { break | txt[0] == '\'': t.Kind = self.lexRune(txt) - t.Id = TokenId.Lit + t.Id = Id.Lit ret t | txt[0] == '"' || txt[0] == '`': t.Kind = self.lexStr() - t.Id = TokenId.Lit + t.Id = Id.Lit ret t - | bytesHasPrefix(txt, TokenKind.LnComment): + | bytesHasPrefix(txt, Kind.LnComment): self.lexLineComment(t) ret t - | bytesHasPrefix(txt, TokenKind.RangLComment): + | bytesHasPrefix(txt, Kind.RangLComment): self.lexRangeComment(t) ret t | self.lexBasicOps(txt, t): @@ -803,7 +803,7 @@ impl lex { // Lex source code into fileset. // Returns nil if f == nil. // Returns nil slice for errors if no any error. -fn Lex(mut f: &File, mode: LexMode): []build::Log { +fn Lex(mut f: &Fileset, mode: Mode): []build::Log { if f == nil { ret nil } diff --git a/std/jule/lex/token.jule b/std/jule/token/token.jule similarity index 78% rename from std/jule/lex/token.jule rename to std/jule/token/token.jule index 328ab063b..a90ac4a49 100644 --- a/std/jule/lex/token.jule +++ b/std/jule/token/token.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use unicode for std::unicode -use utf8 for std::unicode::utf8 -use strings for std::strings +use "std/strings" +use "std/unicode" +use "std/unicode/utf8" // Punctuations. static Puncts: [...]rune = [ @@ -53,63 +53,63 @@ static Spaces: [...]rune = [ ] // Kind list of unary operators. -static UnaryOps: [...]TokenId = [ - TokenId.Minus, - TokenId.Plus, - TokenId.Caret, - TokenId.Excl, - TokenId.Star, - TokenId.Amper, +static UnaryOps: [...]Id = [ + Id.Minus, + Id.Plus, + Id.Caret, + Id.Excl, + Id.Star, + Id.Amper, ] // Kind list of binary operators. -static BinOps: [...]TokenId = [ - TokenId.Plus, - TokenId.Minus, - TokenId.Star, - TokenId.Solidus, - TokenId.Percent, - TokenId.Amper, - TokenId.Vline, - TokenId.Caret, - TokenId.Shl, - TokenId.Shr, - TokenId.Lt, - TokenId.Gt, - TokenId.LtEq, - TokenId.GtEq, - TokenId.DblAmper, - TokenId.DblVline, - TokenId.Eqs, - TokenId.NotEq, +static BinOps: [...]Id = [ + Id.Plus, + Id.Minus, + Id.Star, + Id.Solidus, + Id.Percent, + Id.Amper, + Id.Vline, + Id.Caret, + Id.Shl, + Id.Shr, + Id.Lt, + Id.Gt, + Id.LtEq, + Id.GtEq, + Id.DblAmper, + Id.DblVline, + Id.Eqs, + Id.NotEq, ] // Kind list of weak operators. // These operators are weak, can used as part of expression. -static WeakOps: [...]TokenId = [ - TokenId.TripleDot, - TokenId.Colon, +static WeakOps: [...]Id = [ + Id.TripleDot, + Id.Colon, ] // List of postfix operators. -static PostfixOps: [...]TokenId = [ - TokenId.DblPlus, - TokenId.DblMinus, +static PostfixOps: [...]Id = [ + Id.DblPlus, + Id.DblMinus, ] // List of assign operators. -static AssignOps: [...]TokenId = [ - TokenId.Eq, - TokenId.PlusEq, - TokenId.MinusEq, - TokenId.SolidusEq, - TokenId.StarEq, - TokenId.PercentEq, - TokenId.ShrEq, - TokenId.ShlEq, - TokenId.VlineEq, - TokenId.AmperEq, - TokenId.CaretEq, +static AssignOps: [...]Id = [ + Id.Eq, + Id.PlusEq, + Id.MinusEq, + Id.SolidusEq, + Id.StarEq, + Id.PercentEq, + Id.ShrEq, + Id.ShlEq, + Id.VlineEq, + Id.AmperEq, + Id.CaretEq, ] // Special identifiers. @@ -119,8 +119,8 @@ enum Ident: str { } // Token identities. -enum TokenId: uint { - Na, +enum Id: uint { + NA, Ident, Ret, Semicolon, @@ -201,7 +201,7 @@ enum TokenId: uint { } // Token kinds. -enum TokenKind: str { +enum Kind: str { DblColon: "::", Colon: ":", Semicolon: ";", @@ -283,11 +283,11 @@ enum TokenKind: str { // Token is lexer token. struct Token { - File: &File + File: &Fileset Row: int Column: int Kind: str - Id: TokenId + Id: Id } impl Token { @@ -299,29 +299,29 @@ impl Token { // to handle expression assignments. fn Prec(self): byte { match self.Id { - | TokenId.Star - | TokenId.Percent - | TokenId.Solidus - | TokenId.Shr - | TokenId.Shl - | TokenId.Amper: + | Id.Star + | Id.Percent + | Id.Solidus + | Id.Shr + | Id.Shl + | Id.Amper: ret 5 - | TokenId.Plus - | TokenId.Minus - | TokenId.Vline - | TokenId.Caret: + | Id.Plus + | Id.Minus + | Id.Vline + | Id.Caret: ret 4 - | TokenId.Eqs - | TokenId.NotEq - | TokenId.Eq - | TokenId.Lt - | TokenId.LtEq - | TokenId.Gt - | TokenId.GtEq: + | Id.Eqs + | Id.NotEq + | Id.Eq + | Id.Lt + | Id.LtEq + | Id.Gt + | Id.GtEq: ret 3 - | TokenId.DblAmper: + | Id.DblAmper: ret 2 - | TokenId.DblVline: + | Id.DblVline: ret 1 |: ret 0 @@ -330,7 +330,7 @@ impl Token { } // Reports whether kind is unary operator. -fn IsUnaryOp(id: TokenId): bool { +fn IsUnaryOp(id: Id): bool { for _, op in UnaryOps { if id == op { ret true @@ -340,7 +340,7 @@ fn IsUnaryOp(id: TokenId): bool { } // Reports whether kind is binary operator. -fn IsBinOp(id: TokenId): bool { +fn IsBinOp(id: Id): bool { for _, op in BinOps { if id == op { ret true @@ -350,7 +350,7 @@ fn IsBinOp(id: TokenId): bool { } // Reports whether kind is weak operator. -fn IsWeakOp(id: TokenId): bool { +fn IsWeakOp(id: Id): bool { for _, op in WeakOps { if id == op { ret true @@ -444,6 +444,16 @@ fn IsIdentRune(s: str): bool { ret true } +// Reports whether s is keyword. +fn IsKeyword(s: str): bool { + for _, op in keywords { + if s == op.kind { + ret true + } + } + ret false +} + // Reports whether byte is decimal sequence. fn IsDecimal(b: byte): bool { ret '0' <= b && b <= '9' } @@ -469,19 +479,19 @@ fn IsHex(b: byte): bool { // Reports given token id is allow for // assignment left-expression or not. -fn IsAssign(id: TokenId): bool { - ret (id == TokenId.Ident || - id == TokenId.Cpp || - id == TokenId.Let || - id == TokenId.Mut || - id == TokenId.Self || - id == TokenId.LParent || - id == TokenId.Star || - id == TokenId.Amper) +fn IsAssign(id: Id): bool { + ret (id == Id.Ident || + id == Id.Cpp || + id == Id.Let || + id == Id.Mut || + id == Id.Self || + id == Id.LParent || + id == Id.Star || + id == Id.Amper) } // Reports whether operator kind is postfix operator. -fn IsPostfixOp(id: TokenId): bool { +fn IsPostfixOp(id: Id): bool { for _, op in PostfixOps { if id == op { ret true @@ -491,7 +501,7 @@ fn IsPostfixOp(id: TokenId): bool { } // Reports whether operator kind is assignment operator. -fn IsAssignOp(id: TokenId): bool { +fn IsAssignOp(id: Id): bool { if IsPostfixOp(id) { ret true } diff --git a/std/jule/types/bits.jule b/std/jule/types/bits.jule index 3fc10829a..77a2ab99a 100644 --- a/std/jule/types/bits.jule +++ b/std/jule/types/bits.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use conv for std::conv -use strings for std::strings -use build for std::jule::build +use "std/conv" +use "std/jule/build" +use "std/strings" type bitChecker: fn(v: str, base: int, bit: int): bool @@ -44,10 +44,10 @@ fn checkBit(v: str, bit: int, checker: bitChecker): bool { // Bit-size is determined by runtime. fn RealKindOf(kind: str): str { match kind { - | TypeKind.Int: + | Kind.Int: ret SysInt - | TypeKind.Uint - | TypeKind.Uintptr: + | Kind.Uint + | Kind.Uintptr: ret SysUint |: ret kind @@ -56,25 +56,25 @@ fn RealKindOf(kind: str): str { // Returns kind's bit-size. // Returns -1 if kind is not numeric. -fn BitsizeOf(k: str): int { +fn BitSizeOf(k: str): int { match k { - | TypeKind.I8 - | TypeKind.U8: + | Kind.I8 + | Kind.U8: ret 1 << 3 - | TypeKind.I16 - | TypeKind.U16: + | Kind.I16 + | Kind.U16: ret 1 << 4 - | TypeKind.I32 - | TypeKind.U32 - | TypeKind.F32: + | Kind.I32 + | Kind.U32 + | Kind.F32: ret 1 << 5 - | TypeKind.I64 - | TypeKind.U64 - | TypeKind.F64: + | Kind.I64 + | Kind.U64 + | Kind.F64: ret 1 << 6 - | TypeKind.Uint - | TypeKind.Int - | TypeKind.Uintptr: + | Kind.Uint + | Kind.Int + | Kind.Uintptr: ret BitSize |: ret -1 @@ -87,13 +87,13 @@ fn BitsizeOf(k: str): int { fn IntFromBits(bits: int): str { match bits { | 1 << 3: - ret TypeKind.I8 + ret Kind.I8 | 1 << 4: - ret TypeKind.I16 + ret Kind.I16 | 1 << 5: - ret TypeKind.I32 + ret Kind.I32 | 1 << 6: - ret TypeKind.I64 + ret Kind.I64 |: ret "" } @@ -105,13 +105,13 @@ fn IntFromBits(bits: int): str { fn UintFromBits(bits: int): str { match bits { | 1 << 3: - ret TypeKind.U8 + ret Kind.U8 | 1 << 4: - ret TypeKind.U16 + ret Kind.U16 | 1 << 5: - ret TypeKind.U32 + ret Kind.U32 | 1 << 6: - ret TypeKind.U64 + ret Kind.U64 |: ret "" } @@ -123,9 +123,9 @@ fn UintFromBits(bits: int): str { fn FloatFromBits(bits: int): str { match bits { | 1 << 5: - ret TypeKind.F32 + ret Kind.F32 | 1 << 6: - ret TypeKind.F64 + ret Kind.F64 |: ret "" } @@ -158,7 +158,7 @@ fn CheckBitFloat(val: str, bit: int): bool { // Possible values are: // - 32 for 32-bit // - 64 for 64-bit -fn BitsizeOfFloat(x: f64): int { +fn BitSizeOfFloat(x: f64): int { match { | MinF32 <= x && x <= MaxF32: ret 1 << 5 @@ -174,7 +174,7 @@ fn BitsizeOfFloat(x: f64): int { // - 16 for 16-bit // - 32 for 32-bit // - 64 for 64-bit -fn BitsizeOfInt(x: i64): int { +fn BitSizeOfInt(x: i64): int { match { | MinI8 <= x && x <= MaxI8: ret 1 << 3 @@ -194,7 +194,7 @@ fn BitsizeOfInt(x: i64): int { // - 16 for 16-bit // - 32 for 32-bit // - 64 for 64-bit -fn BitsizeOfUint(x: u64): int { +fn BitSizeOfUint(x: u64): int { match { | x <= MaxU8: ret 1 << 3 @@ -215,12 +215,12 @@ fn UpdateTarget() { match build::Arch { | "arm64" | "amd64": *(&BitSize) = 1 << 6 - *(&SysInt) = TypeKind.I64 - *(&SysUint) = TypeKind.U64 + *(&SysInt) = Kind.I64 + *(&SysUint) = Kind.U64 | "i386": *(&BitSize) = 1 << 5 - *(&SysInt) = TypeKind.I32 - *(&SysUint) = TypeKind.U32 + *(&SysInt) = Kind.I32 + *(&SysUint) = Kind.U32 } } } diff --git a/std/jule/types/comp.jule b/std/jule/types/comp.jule deleted file mode 100644 index 46a198690..000000000 --- a/std/jule/types/comp.jule +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2023-2024 The Jule Programming Language. -// Use of this source code is governed by a BSD 3-Clause -// license that can be found in the LICENSE file. - -// Reports whether i16 is greater than given kind. -fn IsI16Greater(mut k: str): bool { - ret k == TypeKind.I8 -} - -// Reports whether i32 is greater than given kind. -fn IsI32Greater(mut k: str): bool { - ret k == TypeKind.I8 || k == TypeKind.I16 -} - -// Reports whether i64 is greater than given kind. -fn IsI64Greater(mut k: str): bool { - ret k == TypeKind.I8 || - k == TypeKind.I16 || - k == TypeKind.I32 -} - -// Reports whether u16 is greater than given kind. -fn IsU16Greater(mut k: str): bool { - ret k == TypeKind.U8 -} - -// Reports whether u32 is greater than given kind. -fn IsU32Greater(mut k: str): bool { - ret k == TypeKind.U8 || - k == TypeKind.U16 -} - -// Reports whether u64 is greater than given kind. -fn IsU64Greater(mut k: str): bool { - ret k == TypeKind.U8 || - k == TypeKind.U16 || - k == TypeKind.U32 -} - -// Reports whether f32 is greater than given kind. -fn IsF32Greater(k: str): bool { - ret k != TypeKind.F64 -} - -// Reports whether f64 is greater than given kind. -fn IsF64Greater(k: str): bool { - ret true -} - -// Reports whether k1 kind greater than k2 kind. -fn IsGreater(mut k1: str, k2: str): bool { - match k1 { - | TypeKind.Int: - ret IsSigInt(k2) - | TypeKind.Uint: - ret IsUnsigInt(k2) - | TypeKind.Uintptr: - ret IsUnsigInt(k2) - | TypeKind.I16: - ret IsI16Greater(k2) - | TypeKind.I32: - ret IsI32Greater(k2) - | TypeKind.I64: - ret IsI64Greater(k2) - | TypeKind.U16: - ret IsU16Greater(k2) - | TypeKind.U32: - ret IsU32Greater(k2) - | TypeKind.U64: - ret IsU64Greater(k2) - | TypeKind.F32: - ret IsF32Greater(k2) - | TypeKind.F64: - ret IsF64Greater(k2) - | TypeKind.Any: - ret true - |: - ret false - } -} \ No newline at end of file diff --git a/std/jule/types/kind.jule b/std/jule/types/kind.jule index 0c2cbd90d..8d9d978ae 100644 --- a/std/jule/types/kind.jule +++ b/std/jule/types/kind.jule @@ -4,7 +4,7 @@ // Type kinds of primitive types. // These kinds are must match keyword form itself. -enum TypeKind: str { +enum Kind: str { I8: "i8", // Kind of signed 8-bit integer I16: "i16", // Kind of signed 16-bit integer I32: "i32", // Kind of signed 32-bit integer @@ -25,21 +25,21 @@ enum TypeKind: str { // Reports whether kind is signed integer. fn IsSigInt(mut k: str): bool { - ret k == TypeKind.I8 || - k == TypeKind.I16 || - k == TypeKind.I32 || - k == TypeKind.I64 || - k == TypeKind.Int + ret k == Kind.I8 || + k == Kind.I16 || + k == Kind.I32 || + k == Kind.I64 || + k == Kind.Int } // Reports kind is unsigned integer. fn IsUnsigInt(mut k: str): bool { - ret k == TypeKind.U8 || - k == TypeKind.U16 || - k == TypeKind.U32 || - k == TypeKind.U64 || - k == TypeKind.Uint || - k == TypeKind.Uintptr + ret k == Kind.U8 || + k == Kind.U16 || + k == Kind.U32 || + k == Kind.U64 || + k == Kind.Uint || + k == Kind.Uintptr } // Reports whether kind is signed/unsigned integer. @@ -49,7 +49,7 @@ fn IsInt(k: str): bool { // Reports whether kind is float. fn IsFloat(k: str): bool { - ret k == TypeKind.F32 || k == TypeKind.F64 + ret k == Kind.F32 || k == Kind.F64 } // Reports whether kind is numeric. diff --git a/std/jule/types/limits.jule b/std/jule/types/limits.jule index 117c7fbf7..6bdac92d5 100644 --- a/std/jule/types/limits.jule +++ b/std/jule/types/limits.jule @@ -61,13 +61,13 @@ const MaxU64 = 18446744073709551615 fn MinI(mut k: str): i64 { k = RealKindOf(k) match k { - | TypeKind.I8: + | Kind.I8: ret MinI8 - | TypeKind.I16: + | Kind.I16: ret MinI16 - | TypeKind.I32: + | Kind.I32: ret MinI32 - | TypeKind.I64: + | Kind.I64: ret MinI64 |: ret 0 @@ -79,13 +79,13 @@ fn MinI(mut k: str): i64 { fn MaxI(mut k: str): i64 { k = RealKindOf(k) match k { - | TypeKind.I8: + | Kind.I8: ret MaxI8 - | TypeKind.I16: + | Kind.I16: ret MaxI16 - | TypeKind.I32: + | Kind.I32: ret MaxI32 - | TypeKind.I64: + | Kind.I64: ret MaxI64 |: ret 0 @@ -97,13 +97,13 @@ fn MaxI(mut k: str): i64 { fn MaxU(mut k: str): u64 { k = RealKindOf(k) match k { - | TypeKind.U8: + | Kind.U8: ret MaxU8 - | TypeKind.U16: + | Kind.U16: ret MaxU16 - | TypeKind.U32: + | Kind.U32: ret MaxU32 - | TypeKind.U64: + | Kind.U64: ret MaxU64 |: ret 0 @@ -119,9 +119,9 @@ fn Min(mut k: str): f64 { ret f64(i) } match k { - | TypeKind.F32: + | Kind.F32: ret MinF32 - | TypeKind.F64: + | Kind.F64: ret MinF64 |: ret 0 @@ -141,9 +141,9 @@ fn Max(mut k: str): f64 { ret f64(u) } match k { - | TypeKind.F32: + | Kind.F32: ret MaxF32 - | TypeKind.F64: + | Kind.F64: ret MaxF64 |: ret 0 diff --git a/std/maps/maps_test.jule b/std/maps/maps_test.jule index e94bb26de..f5a079ec7 100644 --- a/std/maps/maps_test.jule +++ b/std/maps/maps_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" struct equalCase { m1: map[int]str diff --git a/std/math/big/bits.jule b/std/math/big/bits.jule index f65f88262..72a64a54d 100644 --- a/std/math/big/bits.jule +++ b/std/math/big/bits.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe +use "std/unsafe" // Single bit. type bit: byte diff --git a/std/math/big/bits_test.jule b/std/math/big/bits_test.jule index f9d448b4b..c823f3122 100644 --- a/std/math/big/bits_test.jule +++ b/std/math/big/bits_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static casesTwosComplement: [][]bits = [ [[0, 1, 0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1, 0]], diff --git a/std/math/big/conv.jule b/std/math/big/conv.jule index 1e98dc4aa..7eb12bf08 100644 --- a/std/math/big/conv.jule +++ b/std/math/big/conv.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe +use "std/unsafe" fn u64FromBits(b: bits): u64 { mut u := u64(0) diff --git a/std/math/big/conv_test.jule b/std/math/big/conv_test.jule index de7c8d639..04c59d1a9 100644 --- a/std/math/big/conv_test.jule +++ b/std/math/big/conv_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static casesParseHex = [ [[]byte("0"), []], diff --git a/std/math/big/int.jule b/std/math/big/int.jule index f7fb0419b..5bf131413 100644 --- a/std/math/big/int.jule +++ b/std/math/big/int.jule @@ -36,7 +36,7 @@ impl Int { nat: nat.new[T](i), } |: - panic("std::math::big: Int.new[T]: unimplemented type, this panic call should be unreachable") + panic("big: Int.new[T]: unimplemented type, this panic call should be unreachable") } } @@ -187,7 +187,7 @@ impl Int { // Panics if number is negative. fn Sqrt(self): Int { if self.minus { - panic("std::math::big: Int.Sqrt: square root of negative number") + panic("big: Int.Sqrt: square root of negative number") } ret Int{ minus: false, diff --git a/std/math/big/int_test.jule b/std/math/big/int_test.jule index 64a4ee5e9..0c7e22d49 100644 --- a/std/math/big/int_test.jule +++ b/std/math/big/int_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static casesIntAdd = [ ["+10000100100001", "+10011001101010", "+100011110001011"], diff --git a/std/math/big/nat.jule b/std/math/big/nat.jule index ececc7832..92aa3a9e7 100644 --- a/std/math/big/nat.jule +++ b/std/math/big/nat.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe +use "std/unsafe" // An arbitrary-precision natural number. struct nat { @@ -52,7 +52,7 @@ impl nat { | uint: nat.bits = make(bits, _INT_SIZE) |: - panic("std::math::big: nat.new[T]: T is should be signed or unsigned integer type except uintptr") + panic("big: nat.new[T]: T is should be signed or unsigned integer type except uintptr") } if i < 0 { i = -i @@ -200,7 +200,7 @@ impl nat { // Right operand is 1, remainder is always zero. ret nat.zero() | 0: - panic("std::math::big: division by zero") + panic("big: division by zero") } match self.cmp(y) { | -1: @@ -238,7 +238,7 @@ impl nat { // Right operand is 1, remainder is always zero. ret | 0: - panic("std::math::big: division by zero") + panic("big: division by zero") } match self.cmp(y) { | -1: @@ -290,7 +290,7 @@ impl nat { } ret | y.len() == 0: - panic("std::math::big: division by zero") + panic("big: division by zero") } match self.cmp(y) { | -1: @@ -459,7 +459,7 @@ impl nat { z1, z2 = z2, z1 n++ } - panic("std::math::big: nat.sqrt implementation mistake") + panic("big: nat.sqrt implementation mistake") } // Reports whether number is odd. @@ -476,7 +476,7 @@ impl nat { // The index zero means first bit at right. fn bit(self, i: int): int { if i < 0 { - panic("std::math::big: negative bit index") + panic("big: negative bit index") } if i >= self.len() { ret 0 diff --git a/std/math/big/nat_test.jule b/std/math/big/nat_test.jule index 7ad0d7aea..23182a2c8 100644 --- a/std/math/big/nat_test.jule +++ b/std/math/big/nat_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" static casesNatFromBits = [ "1011010", diff --git a/std/math/cmplx/abs.jule b/std/math/cmplx/abs.jule index 082a3de5f..8661b0c07 100644 --- a/std/math/cmplx/abs.jule +++ b/std/math/cmplx/abs.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/abs.go diff --git a/std/math/cmplx/asin.jule b/std/math/cmplx/asin.jule index 4311d11c1..fdc16ac36 100644 --- a/std/math/cmplx/asin.jule +++ b/std/math/cmplx/asin.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/asin.go and came with this notice. diff --git a/std/math/cmplx/cmplx.jule b/std/math/cmplx/cmplx.jule index 7d2a67c76..910e77068 100644 --- a/std/math/cmplx/cmplx.jule +++ b/std/math/cmplx/cmplx.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // Complex number. struct Cmplx { diff --git a/std/math/cmplx/exp.jule b/std/math/cmplx/exp.jule index 701347b30..f4d0c1f99 100644 --- a/std/math/cmplx/exp.jule +++ b/std/math/cmplx/exp.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/exp.go and came with this notice. diff --git a/std/math/cmplx/log.jule b/std/math/cmplx/log.jule index 11d17be8f..ce552d48c 100644 --- a/std/math/cmplx/log.jule +++ b/std/math/cmplx/log.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/log.go and came with this notice. diff --git a/std/math/cmplx/phase.jule b/std/math/cmplx/phase.jule index 708a1d1d2..4177103b2 100644 --- a/std/math/cmplx/phase.jule +++ b/std/math/cmplx/phase.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/phase.go diff --git a/std/math/cmplx/polar.jule b/std/math/cmplx/polar.jule index a16457cf2..da2291279 100644 --- a/std/math/cmplx/polar.jule +++ b/std/math/cmplx/polar.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/polar.go diff --git a/std/math/cmplx/pow.jule b/std/math/cmplx/pow.jule index 0a1141e22..6df495128 100644 --- a/std/math/cmplx/pow.jule +++ b/std/math/cmplx/pow.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/pow.go and came with this notice. @@ -66,7 +66,7 @@ impl Cmplx { | y.Real() > 0: ret Cmplx.Zero() } - panic("not reached") + panic("cmplx: not reached") } modulus := self.Abs() if modulus == 0 { diff --git a/std/math/cmplx/rect.jule b/std/math/cmplx/rect.jule index 9ffea3cde..80b4d92f9 100644 --- a/std/math/cmplx/rect.jule +++ b/std/math/cmplx/rect.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/rect.go diff --git a/std/math/cmplx/sin.jule b/std/math/cmplx/sin.jule index 6ddf0dcc5..03ad48b73 100644 --- a/std/math/cmplx/sin.jule +++ b/std/math/cmplx/sin.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/sin.go and came with this notice. diff --git a/std/math/cmplx/sqrt.jule b/std/math/cmplx/sqrt.jule index 8f8fda77d..16b1f25cd 100644 --- a/std/math/cmplx/sqrt.jule +++ b/std/math/cmplx/sqrt.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math +use "std/math" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/sqrt.go and came with this notice. diff --git a/std/math/cmplx/tan.jule b/std/math/cmplx/tan.jule index 82efe2518..339047c7a 100644 --- a/std/math/cmplx/tan.jule +++ b/std/math/cmplx/tan.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use math for std::math -use bits for std::math::bits +use "std/math" +use "std/math/bits" // The Jule code is a modified version of the original Go code from // https://github.com/golang/go/blob/go1.20/src/math/cmplx/tan.go and came with this notice. diff --git a/std/math/fma.jule b/std/math/fma.jule index 131c35d64..bc86e1afc 100644 --- a/std/math/fma.jule +++ b/std/math/fma.jule @@ -35,7 +35,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use bits for std::math::bits +use "std/math/bits" fn zero(x: u64): u64 { if x == 0 { diff --git a/std/math/rand/rand.jule b/std/math/rand/rand.jule index 0d5d6ef9d..20b99e52b 100644 --- a/std/math/rand/rand.jule +++ b/std/math/rand/rand.jule @@ -79,7 +79,7 @@ impl Rand { // If n <= 0, it panics. fn Nextn63(self, n: i64): i64 { if n <= 0 { - panic("Rand.Nextn63: invalid argument") + panic("rand: Rand.Nextn63: invalid argument") } if n&(n-1) == 0 { ret self.Next63() & (n - 1) @@ -97,7 +97,7 @@ impl Rand { // If n <= 0, it panics. fn Nextn31(self, n: i32): i32 { if n <= 0 { - panic("Rand.nextn31: invalid argument") + panic("rand: Rand.nextn31: invalid argument") } if n&(n-1) == 0 { ret self.Next31() & (n - 1) @@ -114,7 +114,7 @@ impl Rand { // If n <= 0, it panics. fn Nextn(self, n: int): int { if n <= 0 { - panic("Rand.nextn: invalid argument") + panic("rand: Rand.nextn: invalid argument") } if n <= 1<<31-1 { ret int(self.Nextn31(i32(n))) diff --git a/std/math/trig_reduce.jule b/std/math/trig_reduce.jule index 71c7c9fbb..89a8f6ccd 100644 --- a/std/math/trig_reduce.jule +++ b/std/math/trig_reduce.jule @@ -35,7 +35,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use bits for std::math::bits +use "std/math/bits" // Is the maximum value of x where the reduction using PI/4 // in 3 f64 parts still gives accurate results. This threshold diff --git a/std/mem/builtin_test.jule b/std/mem/builtin_test.jule index 403bd5a86..4aee0d5b2 100644 --- a/std/mem/builtin_test.jule +++ b/std/mem/builtin_test.jule @@ -4,9 +4,9 @@ #build test -use testing for std::testing +use "std/testing" -trait testTrait {} +trait testTrait{} #test fn testFree(t: &testing::T) { diff --git a/std/mem/heap.jule b/std/mem/heap.jule index 81dad990f..2131d9880 100644 --- a/std/mem/heap.jule +++ b/std/mem/heap.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated +use integ "std/jule/integrated" // Wrapper for heap allocation. // Should be freed, occurs memory leak if did not. @@ -40,7 +40,7 @@ impl Heap { // Panics if internal pointer is nil. fn Get(mut self): T { if self.heap == nil { - panic("std::mem: Heap.get: nil pointer dereference") + panic("mem: Heap.get: nil pointer dereference") } ret unsafe { *self.heap } } @@ -49,7 +49,7 @@ impl Heap { // Panics if internal pointer is nil. fn Set(mut self, mut val: T) { if self.heap == nil { - panic("std::mem: Heap.set: nil pointer dereference") + panic("mem: Heap.set: nil pointer dereference") } unsafe { *self.heap = val } } diff --git a/std/net/addr.jule b/std/net/addr.jule index 9a4934b6b..23d1a113a 100644 --- a/std/net/addr.jule +++ b/std/net/addr.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use fastbytes for std::internal::fastbytes -use conv for std::internal::conv +use "std/internal/conv" +use "std/internal/fastbytes" // Address errors. enum AddrError { @@ -113,7 +113,7 @@ fn internetAddr(&net: Network, mut ip: Ip, port: int, zone: str): Addr { | Network.Udp | Network.Udp4 | Network.Udp6: ret &UdpAddr{Ip: ip, Port: port, Zone: zone} |: - panic("unexpected network: " + str(net)) + panic("net: unexpected network: " + str(net)) } } @@ -187,7 +187,7 @@ fn resolveInternetAddr(&net: Network, &addr: str)!: Addr { Port: portnum, } |: - panic("implementation bug, this panic should be unreachable") + panic("net: implementation bug, this panic should be unreachable") } | TcpAddr: mut ipAddr := (TcpAddr)(ip) @@ -261,6 +261,6 @@ fn buildLocalhostAddr(&net: Network, port: int): Addr { Port: port, } |: - panic("implementation bug, this panic should be unreachable") + panic("net: implementation bug, this panic should be unreachable") } } \ No newline at end of file diff --git a/std/net/conv.jule b/std/net/conv.jule index 3702a8afe..c07ae648f 100644 --- a/std/net/conv.jule +++ b/std/net/conv.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use conv for std::internal::conv +use "std/internal/conv" // Converts the next two hex digits of s into a byte. // If s is longer than 2 bytes then the third byte must be e. diff --git a/std/net/ip.jule b/std/net/ip.jule index 504808cad..45f1af7f0 100644 --- a/std/net/ip.jule +++ b/std/net/ip.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fastbytes for std::internal::fastbytes +use "std/internal/fastbytes" +use "std/unsafe" // An IP is a single IP address, wrapper for a slice of bytes. // Functions in this package accept either 4-byte (IPv4) diff --git a/std/net/ip_addr.jule b/std/net/ip_addr.jule index 4f7bc7abd..f8ec6a317 100644 --- a/std/net/ip_addr.jule +++ b/std/net/ip_addr.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use strings for std::internal::strings -use fastbytes for std::internal::fastbytes +use "std/internal/fastbytes" +use "std/internal/strings" +use "std/unsafe" // Returns the address of the IPv4 address given by the 4-bytes representation. fn ipAddrFrom4(addr: []byte): u128 { @@ -71,7 +71,7 @@ fn v6u16(ip: u128, i: byte): u16 { // appendDecimal and appendHex to format IP addresses. const digits = "0123456789abcdef" -fn appendDecimal(mut &s: strings::StrBuilder, x: u8) { +fn appendDecimal(mut &s: strings::Builder, x: u8) { if x >= 100 { s.WriteByte(digits[x/100]) } @@ -81,7 +81,7 @@ fn appendDecimal(mut &s: strings::StrBuilder, x: u8) { s.WriteByte(digits[x%10]) } -fn appendHex(mut &s: strings::StrBuilder, x: u16) { +fn appendHex(mut &s: strings::Builder, x: u16) { if x >= 0x1000 { s.WriteByte(digits[x>>12]) } @@ -96,7 +96,7 @@ fn appendHex(mut &s: strings::StrBuilder, x: u16) { fn str4(ip: u128): str { const Max = len("255.255.255.255") - mut s := strings::StrBuilder.New(Max) + mut s := strings::Builder.New(Max) appendDecimal(s, v4(ip, 0)) s.WriteByte('.') appendDecimal(s, v4(ip, 1)) @@ -109,7 +109,7 @@ fn str4(ip: u128): str { fn str16(ip: u128): str { const Max = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%enp5s0") - mut s := strings::StrBuilder.New(Max) + mut s := strings::Builder.New(Max) mut zeroStart, mut zeroEnd := byte(255), byte(255) mut i := byte(0) diff --git a/std/net/mac.jule b/std/net/mac.jule index b9e086ee6..a6bd74deb 100644 --- a/std/net/mac.jule +++ b/std/net/mac.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use strings for std::internal::strings +use "std/internal/strings" +use "std/unsafe" const hexDigit = "0123456789abcdef" @@ -86,7 +86,7 @@ impl HardwareAddr { if len(self.Addr) == 0 { ret "" } - mut buf := strings::StrBuilder.New(len(self.Addr)*3 - 1) + mut buf := strings::Builder.New(len(self.Addr)*3 - 1) for i, b in self.Addr { if i > 0 { buf.WriteByte(':') diff --git a/std/net/mac_test.jule b/std/net/mac_test.jule index 7ddd8e867..fc7232614 100644 --- a/std/net/mac_test.jule +++ b/std/net/mac_test.jule @@ -4,8 +4,8 @@ #build test -use testing for std::testing -use strings for std::strings +use "std/strings" +use "std/testing" struct caseMacParse { s: str diff --git a/std/net/net.jule b/std/net/net.jule index d5617809b..0590f3908 100644 --- a/std/net/net.jule +++ b/std/net/net.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use time for std::time +use "std/time" // Network names. enum Network: str { diff --git a/std/net/sock.jule b/std/net/sock.jule index f379702a8..3a60f87ac 100644 --- a/std/net/sock.jule +++ b/std/net/sock.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use time for std::time -use sys for std::sys +use "std/sys" +use "std/time" // Listens the address on the named network. // It will forward any exceptional from network connectors. diff --git a/std/net/sock_unix.jule b/std/net/sock_unix.jule index 3e9c5e088..b84ac07f3 100644 --- a/std/net/sock_unix.jule +++ b/std/net/sock_unix.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use runtime for std::runtime -use mem for std::mem -use sys for std::sys -use time for std::time -use integ for std::jule::integrated +use integ "std/jule/integrated" +use "std/mem" +use "std/runtime" +use "std/sys" +use "std/time" type netHandle: int type addrLen: u32 diff --git a/std/net/sock_windows.jule b/std/net/sock_windows.jule index 968aad31e..4f873a441 100644 --- a/std/net/sock_windows.jule +++ b/std/net/sock_windows.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use runtime for std::runtime -use mem for std::mem -use sys for std::sys -use time for std::time -use integ for std::jule::integrated +use integ "std/jule/integrated" +use "std/mem" +use "std/runtime" +use "std/sys" +use "std/time" type netHandle: uint type addrLen: integ::Int @@ -127,6 +127,6 @@ fn init() { verReq := sys::MakeWord(2, 2) r := unsafe { sys::WSAStartup(verReq, &wsaData) } if r != 0 { - panic("syd::net [windows specific]: WSAStartup failed") + panic("net: WSAStartup failed (Windows specific)") } } \ No newline at end of file diff --git a/std/net/tcp.jule b/std/net/tcp.jule index 4285b800e..12e300505 100644 --- a/std/net/tcp.jule +++ b/std/net/tcp.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use conv for std::internal::conv +use "std/internal/conv" // Represents the address of a TCP end point. struct TcpAddr { diff --git a/std/net/tcp_conn.jule b/std/net/tcp_conn.jule index 789292b1d..bb2201a66 100644 --- a/std/net/tcp_conn.jule +++ b/std/net/tcp_conn.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use runtime for std::runtime -use io for std::io -use time for std::time -use sys for std::sys +use "std/io" +use "std/runtime" +use "std/sys" +use "std/time" // TCP connection. // In most cases, represents TCP client. @@ -33,7 +33,7 @@ impl TcpConn { // All exceptionals are error code of implementation. fn Read(mut self, mut buf: []byte)!: int { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpConn.Read: connection is closed") + panic("net: TcpConn.Read: connection is closed") } if len(buf) == 0 { ret 0 @@ -54,7 +54,7 @@ impl TcpConn { // All exceptionals are error code of implementation. fn Write(mut self, buf: []byte)!: int { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpConn.Write: connection is closed") + panic("net: TcpConn.Write: connection is closed") } if len(buf) == 0 { ret 0 @@ -74,7 +74,7 @@ impl TcpConn { // All exceptionals are error code of implementation. fn SetReadTimeout(mut self, timeout: time::DurInt)! { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpConn.SetReadTimeout: connection is closed") + panic("net: TcpConn.SetReadTimeout: connection is closed") } setSocketTimeout(self.handle, sys::SO_RCVTIMEO, timeout) else { error(error) } } @@ -86,7 +86,7 @@ impl TcpConn { // All exceptionals are error code of implementation. fn SetWriteTimeout(mut self, timeout: time::DurInt)! { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpConn.SetReadTimeout: connection is closed") + panic("net: TcpConn.SetReadTimeout: connection is closed") } setSocketTimeout(self.handle, sys::SO_SNDTIMEO, timeout) else { error(error) } } diff --git a/std/net/tcp_listener.jule b/std/net/tcp_listener.jule index ed85556e6..57b590bca 100644 --- a/std/net/tcp_listener.jule +++ b/std/net/tcp_listener.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use mem for std::mem -use sys for std::sys -use time for std::time +use "std/mem" +use "std/sys" +use "std/time" // TCP listener. // In most cases, represents TCP server. @@ -47,7 +47,7 @@ impl TcpListener { // Panics if connection is closed. fn Accept(self)!: Conn { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpListener.Accept: connection is not open") + panic("net: TcpListener.Accept: connection is not open") } if self.v6 { // IPv6 mut clientAddr := sys::SockaddrIn6{} diff --git a/std/net/udp.jule b/std/net/udp.jule index ed4d7003b..31986ca0e 100644 --- a/std/net/udp.jule +++ b/std/net/udp.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use conv for std::internal::conv +use "std/internal/conv" // Represents the address of a UDP end point. struct UdpAddr { diff --git a/std/net/udp_conn.jule b/std/net/udp_conn.jule index 7d592e2a4..1e9e28d0f 100644 --- a/std/net/udp_conn.jule +++ b/std/net/udp_conn.jule @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use io for std::io -use mem for std::mem -use time for std::time -use sys for std::sys +use "std/io" +use "std/mem" +use "std/sys" +use "std/time" // UDP connection. // This structure represents server and client connections. @@ -52,7 +52,7 @@ impl UdpConn { // All exceptionals are error code of implementation. fn Read(mut self, mut buf: []byte)!: int { if self.handle == sys::INVALID_SOCKET { - panic("std::net: UdpConn.Read: connection is closed") + panic("net: UdpConn.Read: connection is closed") } if len(buf) == 0 { ret 0 @@ -65,7 +65,7 @@ impl UdpConn { // All exceptionals are error code of implementation. fn Write(mut self, buf: []byte)!: int { if self.handle == sys::INVALID_SOCKET { - panic("std::net: UdpConn.Write: connection is closed") + panic("net: UdpConn.Write: connection is closed") } if len(buf) == 0 { ret 0 @@ -80,7 +80,7 @@ impl UdpConn { // All exceptionals are error code of implementation. fn SetReadTimeout(mut self, timeout: time::DurInt)! { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpConn.SetReadTimeout: connection is closed") + panic("net: TcpConn.SetReadTimeout: connection is closed") } setSocketTimeout(self.handle, sys::SO_RCVTIMEO, timeout) else { error(error) } } @@ -92,7 +92,7 @@ impl UdpConn { // All exceptionals are error code of implementation. fn SetWriteTimeout(mut self, timeout: time::DurInt)! { if self.handle == sys::INVALID_SOCKET { - panic("std::net: TcpConn.SetReadTimeout: connection is closed") + panic("net: TcpConn.SetReadTimeout: connection is closed") } setSocketTimeout(self.handle, sys::SO_SNDTIMEO, timeout) else { error(error) } } diff --git a/std/process/cmd_unix.jule b/std/process/cmd_unix.jule index 1af1097b0..e948648fa 100644 --- a/std/process/cmd_unix.jule +++ b/std/process/cmd_unix.jule @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use fastbytes for std::internal::fastbytes -use conv for std::internal::conv -use sys for std::sys +use "std/internal/conv" +use "std/internal/fastbytes" +use integ "std/jule/integrated" +use "std/sys" + cpp use "" cpp use "" cpp use "" @@ -80,7 +81,7 @@ fn setenv(&envv: []str)! { impl Cmd { fn spawn(self)! { if self.attrs.pid != invalidPid { - panic("command is already spawned") + panic("process: command is already spawned") } path := self.path let pipe: [2]integ::Int @@ -122,7 +123,7 @@ impl Cmd { fn kill(self)! { if self.attrs.pid == invalidPid { - panic("command is not spawned") + panic("process: command is not spawned") } if cpp.kill(self.attrs.pid, 1) != 0 { error(getLastProcessError()) @@ -132,7 +133,7 @@ impl Cmd { fn wait(self)!: int { if self.attrs.pid == invalidPid { - panic("command is not spawned") + panic("process: command is not spawned") } mut stat := 0 unsafe { diff --git a/std/process/cmd_windows.jule b/std/process/cmd_windows.jule index 6a561bb52..a6497a2b9 100644 --- a/std/process/cmd_windows.jule +++ b/std/process/cmd_windows.jule @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -use fastbytes for std::internal::fastbytes -use mem for std::mem -use sys for std::sys -use strings for std::internal::strings -use utf16 for std::unicode::utf16 +use "std/internal/fastbytes" +use "std/internal/strings" +use integ "std/jule/integrated" +use "std/mem" +use "std/sys" +use "std/unicode/utf16" cpp type HANDLE: *unsafe @@ -40,7 +40,7 @@ struct cmdAttrs { impl Cmd { fn spawn(self)! { if self.attrs.hProcess != nil { - panic("command is already spawned") + panic("process: command is already spawned") } mut startupInfo := cpp.STARTUPINFOW{} mut processInfo := cpp.PROCESS_INFORMATION{} @@ -71,7 +71,7 @@ impl Cmd { fn kill(self)! { if self.attrs.hProcess == nil { - panic("command is not spawned") + panic("process: command is not spawned") } if unsafe { cpp.TerminateProcess(self.attrs.hProcess, 0) } { self.attrs.hProcess = nil @@ -83,7 +83,7 @@ impl Cmd { fn wait(self)!: int { if self.attrs.hProcess == nil { - panic("command is not spawned") + panic("process: command is not spawned") } unsafe { cpp.WaitForSingleObject(self.attrs.hProcess, cpp.INFINITE) } mut exitCode := integ::LongLong(-1) @@ -99,7 +99,7 @@ impl Cmd { } // Escapes the string s, as per escapeArg, appends the result to s. -fn appendEscapeArg(mut &s: strings::StrBuilder, arg: str) { +fn appendEscapeArg(mut &s: strings::Builder, arg: str) { if len(arg) == 0 { s.WriteStr(`""`) ret @@ -161,7 +161,7 @@ fn appendEscapeArg(mut &s: strings::StrBuilder, arg: str) { // Builds a command line out of args by escaping "special" // characters and joining the arguments with spaces. fn makeCmdLine(args: []str): str { - mut s := strings::StrBuilder.New(1 << 4) + mut s := strings::Builder.New(1 << 4) for _, arg in args { if s.Len() > 0 { s.WriteByte(' ') diff --git a/std/process/error_unix.jule b/std/process/error_unix.jule index 9d6d58dcf..96f1df8d9 100644 --- a/std/process/error_unix.jule +++ b/std/process/error_unix.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" fn processErrorFromCode(code: int): ProcessError { match code { diff --git a/std/process/error_windows.jule b/std/process/error_windows.jule index 8032176b4..95821b78e 100644 --- a/std/process/error_windows.jule +++ b/std/process/error_windows.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" const _ERROR_FILE_NOT_FOUND = 0x2 const _ERROR_PATH_NOT_FOUND = 0x3 diff --git a/std/process/process.jule b/std/process/process.jule index 657748148..994aeeaee 100644 --- a/std/process/process.jule +++ b/std/process/process.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys -use runtime for std::runtime +use "std/runtime" +use "std/sys" // Causes the current program to exit with the given status code. // Conventionally, code zero indicates success, non-zero an error. diff --git a/std/runtime/README.md b/std/runtime/README.md index 1d0f39cba..ffd4fb55a 100644 --- a/std/runtime/README.md +++ b/std/runtime/README.md @@ -1,4 +1,4 @@ -# `std::runtime` +# `std/runtime` This package contains runtime functionalities for runtime of the Jule programs.\ It mostly defines private functionalities but any standard library package may able to access them, unlike non-standard packages. \ No newline at end of file diff --git a/std/runtime/conv.jule b/std/runtime/conv.jule index 663146c49..37ebed6c1 100644 --- a/std/runtime/conv.jule +++ b/std/runtime/conv.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use comptime for std::comptime -use integ for std::jule::integrated +use "std/comptime" +use integ "std/jule/integrated" +use "std/unsafe" // Returns pointer in string form. #export "__jule_ptrToStr" diff --git a/std/runtime/env_darwin.jule b/std/runtime/env_darwin.jule index 39fceb1f9..fcb3e516f 100644 --- a/std/runtime/env_darwin.jule +++ b/std/runtime/env_darwin.jule @@ -2,8 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys -use integ for std::jule::integrated +use integ "std/jule/integrated" +use "std/sys" + cpp use "" cpp unsafe fn _NSGetExecutablePath(b: *integ::Char, *u32): bool diff --git a/std/runtime/env_linux.jule b/std/runtime/env_linux.jule index 407a80994..79c9e8cbb 100644 --- a/std/runtime/env_linux.jule +++ b/std/runtime/env_linux.jule @@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use sys for std::sys -use integ for std::jule::integrated +use integ "std/jule/integrated" +use "std/sys" +use "std/unsafe" + cpp use "" cpp unsafe fn readlink(*integ::Char, *integ::Char, int): int diff --git a/std/runtime/env_unix.jule b/std/runtime/env_unix.jule index 75a9b0dd8..3286c2e5f 100644 --- a/std/runtime/env_unix.jule +++ b/std/runtime/env_unix.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe +use "std/unsafe" fn args(): []str { mut args := make([]str, argc) diff --git a/std/runtime/env_windows.jule b/std/runtime/env_windows.jule index b647d72d8..654d16c74 100644 --- a/std/runtime/env_windows.jule +++ b/std/runtime/env_windows.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys -use integ for std::jule::integrated +use integ "std/jule/integrated" +use "std/sys" cpp fn GetCommandLineW(): *integ::Wchar cpp unsafe fn CommandLineToArgvW(*integ::Wchar, *integ::Int): **integ::Wchar diff --git a/std/runtime/io_unix.jule b/std/runtime/io_unix.jule index 8fc802a3a..f3b5408cd 100644 --- a/std/runtime/io_unix.jule +++ b/std/runtime/io_unix.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys +use "std/sys" // This information adopted from the Go programming language: // diff --git a/std/runtime/io_windows.jule b/std/runtime/io_windows.jule index 224442412..e49886827 100644 --- a/std/runtime/io_windows.jule +++ b/std/runtime/io_windows.jule @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use sys for std::sys -use integ for std::jule::integrated -use utf8 for std::unicode::utf8 -use utf16 for std::unicode::utf16 +use integ "std/jule/integrated" +use "std/sys" +use "std/unicode/utf16" +use "std/unicode/utf8" +use "std/unsafe" fn _handleRW(&b: []byte) {} diff --git a/std/runtime/map.jule b/std/runtime/map.jule index 52b647a59..2aa6b3fd7 100644 --- a/std/runtime/map.jule +++ b/std/runtime/map.jule @@ -30,8 +30,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::unsafe -use bits for std::math::bits +use "std/math/bits" +use "std/unsafe" const groupSize = 8 const maxAvgGroupLoad = 4 diff --git a/std/runtime/maphash.jule b/std/runtime/maphash.jule index 1caa9f421..5d20d9074 100644 --- a/std/runtime/maphash.jule +++ b/std/runtime/maphash.jule @@ -27,7 +27,7 @@ // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -use binary for std::encoding::binary +use "std/encoding/binary" const k0 = 0xc3a5c85c97cb3127 const k1 = 0xb492b66fbe98f273 diff --git a/std/runtime/panic.jule b/std/runtime/panic.jule index b8d0ff35b..012bfef81 100644 --- a/std/runtime/panic.jule +++ b/std/runtime/panic.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use sys for std::sys +use "std/sys" +use "std/unsafe" // Exit code of panic calls. const panicExit = 2 diff --git a/std/runtime/rc.jule b/std/runtime/rc.jule index fa715bb3e..a8eb06667 100644 --- a/std/runtime/rc.jule +++ b/std/runtime/rc.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use comptime for std::comptime +use "std/comptime" // Type of reference counting data. type _RCType: uint diff --git a/std/runtime/strings.jule b/std/runtime/strings.jule index 5bdf1ac59..187f1abd7 100644 --- a/std/runtime/strings.jule +++ b/std/runtime/strings.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use utf8 for std::unicode::utf8 +use "std/unicode/utf8" +use "std/unsafe" // See [std::strings::{Compare}] function for documentation. #export "__jule_compareStr" diff --git a/std/runtime/thread_unix.jule b/std/runtime/thread_unix.jule index 4110ecb9d..0bfb3800d 100644 --- a/std/runtime/thread_unix.jule +++ b/std/runtime/thread_unix.jule @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated +use integ "std/jule/integrated" + cpp use "" cpp unsafe fn pthread_create(*cpp.pthread_t, *unsafe, *unsafe, *unsafe): int diff --git a/std/runtime/thread_windows.jule b/std/runtime/thread_windows.jule index 75ba572ad..54730557f 100644 --- a/std/runtime/thread_windows.jule +++ b/std/runtime/thread_windows.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use sys for std::sys -use integ for std::jule::integrated +use integ "std/jule/integrated" +use "std/sys" cpp unsafe fn CreateThread(*unsafe, int, *unsafe, *unsafe, int, *unsafe): *unsafe diff --git a/std/slices/slices_test.jule b/std/slices/slices_test.jule index 1886aada1..1dedb2308 100644 --- a/std/slices/slices_test.jule +++ b/std/slices/slices_test.jule @@ -4,7 +4,7 @@ #build test -use testing for std::testing +use "std/testing" #test fn testEqual(t: &testing::T) { diff --git a/std/slices/sort.jule b/std/slices/sort.jule index d64aad3fe..267a7a91d 100644 --- a/std/slices/sort.jule +++ b/std/slices/sort.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use bits for std::math::bits -use cmp for std::internal::cmp +use "std/internal/cmp" +use "std/math/bits" // Sorts a slice of any ordered type in ascending order. // When sorting floating-point numbers, NaNs are ordered before other values. diff --git a/std/slices/sort_test.jule b/std/slices/sort_test.jule index 28838d266..e637803c0 100644 --- a/std/slices/sort_test.jule +++ b/std/slices/sort_test.jule @@ -4,8 +4,8 @@ #build test -use testing for std::testing -use math for std::math +use "std/math" +use "std/testing" static caseInts = [74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586] static caseF64s = [74.3, 59.0, math::Inf(1), 238.2, -784.0, 2.3, math::Inf(-1), 9845.768, -959.7485, 905, 7.8, 7.8, 74.3, 59.0, math::Inf(1), 238.2, -784.0, 2.3] diff --git a/std/slices/sortordered.jule b/std/slices/sortordered.jule index e02df76f0..65254d79e 100644 --- a/std/slices/sortordered.jule +++ b/std/slices/sortordered.jule @@ -35,8 +35,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use bits for std::math::bits -use cmp for std::internal::cmp +use "std/internal/cmp" +use "std/math/bits" enum sortedHint { Unknown, diff --git a/std/strings/builder.jule b/std/strings/builder.jule index e9cd43948..85bd184a3 100644 --- a/std/strings/builder.jule +++ b/std/strings/builder.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use strings for std::internal::strings +use "std/internal/strings" // String builder for efficient concatenation. // Optimized for single string building not for repeated use. -type StrBuilder: strings::StrBuilder \ No newline at end of file +type Builder: strings::Builder \ No newline at end of file diff --git a/std/strings/compare.jule b/std/strings/compare.jule index 882a08e17..83d74cfb1 100644 --- a/std/strings/compare.jule +++ b/std/strings/compare.jule @@ -35,9 +35,9 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use utf8 for std::unicode::utf8 -use unicode for std::unicode -use runtime for std::runtime +use "std/runtime" +use "std/unicode" +use "std/unicode/utf8" // Returns an integer comparing two strings lexicographically. // The result will be 0 if a == b, -1 if a < b, and +1 if a > b. diff --git a/std/strings/strings.jule b/std/strings/strings.jule index e3b4cf0ca..a8d4d749d 100644 --- a/std/strings/strings.jule +++ b/std/strings/strings.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use unicode for std::unicode -use utf8 for std::unicode::utf8 -use fastbytes for std::internal::fastbytes +use "std/internal/fastbytes" +use "std/unicode" +use "std/unicode/utf8" // Returns string that equals to concatenation of n-count s. // Returns empty string is n <= 0. @@ -13,9 +13,9 @@ fn Repeat(s: str, mut n: int): str { ret "" } if len(s) > int.Max/n { - panic("std::strings: repeat: integer buffer size overflow") + panic("strings: repeat: integer buffer size overflow") } - mut ss := StrBuilder.New(len(s) * n) + mut ss := Builder.New(len(s) * n) for n > 0; n-- { ss.WriteStr(s) } @@ -294,7 +294,7 @@ fn Replace(s: str, sub: str, new: str, mut n: int): str { n = m } - mut ss := StrBuilder.New((len(s) + n*(len(new)-len(sub))) + 1) + mut ss := Builder.New((len(s) + n*(len(new)-len(sub))) + 1) mut i := 0 for n > 0; n-- { j := FindAt(s, sub, i) @@ -313,7 +313,7 @@ fn Replace(s: str, sub: str, new: str, mut n: int): str { // according to the mapping function. If mapping returns a negative value, // the character is dropped from the string with no replacement. fn Map(s: str, mapping: fn(mut rune): rune): str { - mut ss := StrBuilder.New(len(s) + 1) + mut ss := Builder.New(len(s) + 1) mut i := 0 for i < len(s) { mut r, n := utf8::DecodeRuneStr(s[i:]) @@ -384,7 +384,7 @@ fn Join(parts: []str, sep: str): str { n += len(part) n++ } - mut s := StrBuilder.New(n + 1) + mut s := Builder.New(n + 1) s.WriteStr(parts[0]) for _, part in parts[1:] { s.WriteStr(sep) diff --git a/std/sync/atomic/atomic.jule b/std/sync/atomic/atomic.jule index 4ec2fc01f..a5b54369f 100644 --- a/std/sync/atomic/atomic.jule +++ b/std/sync/atomic/atomic.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use runtime for std::runtime +use "std/runtime" // Memory order for atomic operations. // Specifies how memory accesses. @@ -38,11 +38,11 @@ enum MemoryOrder { SeqCst: runtime::atomicSeqCst, } -struct atomicNumber[T] { +struct number[T] { n: T } -impl atomicNumber { +impl number { // Atomically stores new value and returns the previous value. fn Swap(mut self, new: T, order: MemoryOrder): (old: T) { ret unsafe { runtime::atomicSwap[T](&self.n, &new, order) } @@ -69,45 +69,45 @@ impl atomicNumber { } } -impl atomicNumber { +impl number { // Returns new atomic instance for type with initializer value. - static fn New(n: T): atomicNumber[T] { - ret atomicNumber[T]{n: n} + static fn New(n: T): number[T] { + ret number[T]{n: n} } } // Type alias for private wrapper structure for i8 type. -type AtomicI8: atomicNumber[i8] +type I8: number[i8] // Type alias for private wrapper structure for i16 type. -type AtomicI16: atomicNumber[i16] +type I16: number[i16] // Type alias for private wrapper structure for i32 type. -type AtomicI32: atomicNumber[i32] +type I32: number[i32] // Type alias for private wrapper structure for i64 type. -type AtomicI64: atomicNumber[i64] +type I64: number[i64] // Type alias for private wrapper structure for int type. -type AtomicInt: atomicNumber[int] +type Int: number[int] // Type alias for private wrapper structure for u8 type. -type AtomicU8: atomicNumber[u8] +type U8: number[u8] // Type alias for private wrapper structure for u16 type. -type AtomicU16: atomicNumber[u16] +type U16: number[u16] // Type alias for private wrapper structure for u32 type. -type AtomicU32: atomicNumber[u32] +type U32: number[u32] // Type alias for private wrapper structure for u64 type. -type AtomicU64: atomicNumber[u64] +type U64: number[u64] // Type alias for private wrapper structure for uint type. -type AtomicUint: atomicNumber[uint] +type Uint: number[uint] // Type aliases for private wrapper structure for uintptr type. -type AtomicUintptr: atomicNumber[uintptr] +type Uintptr: number[uintptr] // Atomically stores new into addr and returns the previous addr value. // Only integer types are supported. diff --git a/std/sync/mutex.jule b/std/sync/mutex.jule index 6fabd48db..7aec20077 100644 --- a/std/sync/mutex.jule +++ b/std/sync/mutex.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use atomic for std::sync::atomic +use "std/sync/atomic" const mutexUnlocked = 0 const mutexLocked = 1 @@ -29,7 +29,8 @@ impl Mutex { // another thread, it stops the execution of the // algorithm to seize it and waits to lock the mutex. fn Lock(self) { - for !self.TryLock() {} + for !self.TryLock() { + } } // Unlock the mutex you locked and make it open diff --git a/std/sync/once.jule b/std/sync/once.jule index 4a51d4ff8..308d749c0 100644 --- a/std/sync/once.jule +++ b/std/sync/once.jule @@ -35,7 +35,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ==================================================== -use atomic for std::sync::atomic +use "std/sync/atomic" // Once is an object that will perform exactly one action. // A Once must not be copied after first use. @@ -45,7 +45,7 @@ struct Once { // The hot path is inlined at every call site. // Placing done first allows more compact instructions on some architectures (amd64/i386), // and fewer instructions (to calculate offset) on other architectures. - mut done: atomic::AtomicU8 + mut done: atomic::U8 mut m: Mutex } diff --git a/std/sync/waitgroup.jule b/std/sync/waitgroup.jule index 263eb0b0f..6b585786d 100644 --- a/std/sync/waitgroup.jule +++ b/std/sync/waitgroup.jule @@ -2,20 +2,20 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use atomic for std::sync::atomic +use "std/sync/atomic" // Do not copy an instance of WaitGroup, use a ref or pointer instead. // // usage: in main thread: -// `wg: std::sync::WaitGroup -// `wg.add(delta)` before starting tasks with `co ...` -// `wg.wait()` to wait for all tasks to have finished +// `wg: sync::WaitGroup +// `wg.Add(delta)` before starting tasks with `co ...` +// `wg.Eait()` to wait for all tasks to have finished // // in each parallel job: // `wg.done()` when finished struct WaitGroup { - taskN: atomic::AtomicU32 // current task count - reading/writing should be atomic - waitN: atomic::AtomicU32 // current wait count - reading/writing should be atomic + taskN: atomic::U32 // current task count - reading/writing should be atomic + waitN: atomic::U32 // current wait count - reading/writing should be atomic } impl WaitGroup { @@ -31,7 +31,7 @@ impl WaitGroup { oldTask := int(self.taskN.Add(u32(delta), atomic::MemoryOrder.Relaxed)) nTask := oldTask + delta if nTask < 0 { - panic("std:sync: WaitGroup.Add: negative number of tasks") + panic("sync: WaitGroup.Add: negative number of tasks") } // Number of tasks still greater than zero. @@ -68,6 +68,7 @@ impl WaitGroup { self.waitN.Add(1, atomic::MemoryOrder.Relaxed) // Wait for clearing waiters. - for self.waitN.Load(atomic::MemoryOrder.Relaxed) != 0 {} + for self.waitN.Load(atomic::MemoryOrder.Relaxed) != 0 { + } } } \ No newline at end of file diff --git a/std/sys/net.jule b/std/sys/net.jule index bd0b69480..1b472d615 100755 --- a/std/sys/net.jule +++ b/std/sys/net.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated +use integ "std/jule/integrated" #typedef cpp struct fd_set{} diff --git a/std/sys/net_unix.jule b/std/sys/net_unix.jule index b6c653d74..854f38532 100755 --- a/std/sys/net_unix.jule +++ b/std/sys/net_unix.jule @@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated -cpp use "" -cpp use "" -cpp use "" +use integ "std/jule/integrated" + cpp use "" +cpp use "" +cpp use "" +cpp use "" #cdef cpp fn FD_ZERO(*cpp.fd_set) diff --git a/std/sys/net_windows.jule b/std/sys/net_windows.jule index 3b72a7f57..5c594e425 100755 --- a/std/sys/net_windows.jule +++ b/std/sys/net_windows.jule @@ -7,7 +7,8 @@ #pass "-lws2_32" -use integ for std::jule::integrated +use integ "std/jule/integrated" + cpp use "" cpp use "" diff --git a/std/sys/syscall_unix.jule b/std/sys/syscall_unix.jule index f7f887940..c82806966 100644 --- a/std/sys/syscall_unix.jule +++ b/std/sys/syscall_unix.jule @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated +use integ "std/jule/integrated" + cpp use "" cpp use "" cpp use "" diff --git a/std/sys/syscall_windows.jule b/std/sys/syscall_windows.jule index 6bc32e33e..fd1cab3ab 100644 --- a/std/sys/syscall_windows.jule +++ b/std/sys/syscall_windows.jule @@ -4,10 +4,11 @@ #pass "-lshell32" // Link shell32.lib -use integ for std::jule::integrated -cpp use "" +use integ "std/jule/integrated" + cpp use "" cpp use "" +cpp use "" cpp type DWORD: u32 cpp type HANDLE: *unsafe diff --git a/std/testing/t.jule b/std/testing/t.jule index c58bac71b..94a5b24d2 100644 --- a/std/testing/t.jule +++ b/std/testing/t.jule @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::unsafe -use fmt for std::internal::fmt +use "std/internal/fmt" +use "std/unsafe" enum status: byte { Na: 0x0, @@ -35,7 +35,7 @@ impl T { // Does not breaks scope execution. fn Fail(self) { if self.s == status.Skip { - panic("std::testing: T.fail: failed test that already skipped") + panic("testing: T.fail: failed test that already skipped") } self.s = status.Fail } @@ -49,7 +49,7 @@ impl T { // Does not breaks scope execution. fn Skip(self) { if self.s == status.Skip { - panic("std::testing: T.skip: skipped test that already failed") + panic("testing: T.skip: skipped test that already failed") } self.s = status.Skip } diff --git a/std/unicode/utf16/test/utf16_test.jule b/std/unicode/utf16/test/utf16_test.jule index 7fbed4f93..278c1fd01 100644 --- a/std/unicode/utf16/test/utf16_test.jule +++ b/std/unicode/utf16/test/utf16_test.jule @@ -36,9 +36,9 @@ #build test -use testing for std::testing -use unicode for std::unicode -use utf16 for std::unicode::utf16 +use "std/testing" +use "std/unicode" +use "std/unicode/utf16" struct encodeTest { inp: []rune @@ -48,9 +48,11 @@ struct encodeTest { static encodeCases: []encodeTest = [ {[1, 2, 3, 4], [1, 2, 3, 4]}, {[0xffff, 0x10000, 0x10001, 0x12345, 0x10ffff], - [0xffff, 0xd800, 0xdc00, 0xd800, 0xdc01, 0xd808, 0xdf45, 0xdbff, 0xdfff]}, + [0xffff, 0xd800, 0xdc00, 0xd800, 0xdc01, 0xd808, 0xdf45, 0xdbff, 0xdfff], + }, {['a', 'b', 0xd7ff, 0xd800, 0xdfff, 0xe000, 0x110000, -1], - ['a', 'b', 0xd7ff, 0xfffd, 0xfffd, 0xe000, 0xfffd, 0xfffd]}, + ['a', 'b', 0xd7ff, 0xfffd, 0xfffd, 0xe000, 0xfffd, 0xfffd], + }, ] fn eq[S: []E, E](a: S, b: S): bool { @@ -132,7 +134,8 @@ struct decodeTest { static decodeCases: []decodeTest = [ {[1, 2, 3, 4], [1, 2, 3, 4]}, {[0xffff, 0xd800, 0xdc00, 0xd800, 0xdc01, 0xd808, 0xdf45, 0xdbff, 0xdfff], - [0xffff, 0x10000, 0x10001, 0x12345, 0x10ffff]}, + [0xffff, 0x10000, 0x10001, 0x12345, 0x10ffff], + }, {[0xd800, 'a'], [0xfffd, 'a']}, {[0xdfff], [0xfffd]}, ] @@ -158,7 +161,7 @@ static decodeRuneCases: []decodeRuneTest = [ {0xd800, 0xdc01, 0x10001}, {0xd808, 0xdf45, 0x12345}, {0xdbff, 0xdfff, 0x10ffff}, - {0xd800, 'a', 0xfffd}, // illegal, replacement rune substituted + {0xd800, 'a', 0xfffd}, // illegal, replacement rune substituted ] #test @@ -185,11 +188,11 @@ static surrogateCases: []surrogateTest = [ {'\U0001D11E', false}, // MUSICAL SYMBOL G CLEF {'\U0010FFFD', false}, // PRIVATE USE CHARACTER-10FFFD (last Unicode code point) - {0xd7ff, false}, // surr1-1 - {0xd800, true}, // surr1 - {0xdc00, true}, // surr2 - {0xe000, false}, // surr3 - {0xdfff, true}, // surr3-1 + {0xd7ff, false}, // surr1-1 + {0xd800, true}, // surr1 + {0xdc00, true}, // surr2 + {0xe000, false}, // surr3 + {0xdfff, true}, // surr3-1 ] #test diff --git a/std/unicode/utf8/test/utf8_test.jule b/std/unicode/utf8/test/utf8_test.jule index 64061ef0c..3161fcb5a 100644 --- a/std/unicode/utf8/test/utf8_test.jule +++ b/std/unicode/utf8/test/utf8_test.jule @@ -36,10 +36,10 @@ #build test -use std::unsafe -use testing for std::testing -use utf8 for std::unicode::utf8 -use fastbytes for std::internal::fastbytes +use "std/internal/fastbytes" +use "std/testing" +use "std/unicode/utf8" +use "std/unsafe" struct Utf8Map { r: rune @@ -69,8 +69,8 @@ static utf8map: []Utf8Map = [ {0x0801, "\xe0\xa0\x81"}, {0x1000, "\xe1\x80\x80"}, {0xd000, "\xed\x80\x80"}, - {0xd7ff, "\xed\x9f\xbf"}, // last code point before surrogate half. - {0xe000, "\xee\x80\x80"}, // first code point after surrogate half. + {0xd7ff, "\xed\x9f\xbf"}, // last code point before surrogate half. + {0xe000, "\xee\x80\x80"}, // first code point after surrogate half. {0xfffe, "\xef\xbf\xbe"}, {0xffff, "\xef\xbf\xbf"}, {0x10000, "\xf0\x90\x80\x80"}, @@ -106,7 +106,7 @@ fn testFullRune(t: &testing::T) { if !utf8::FullRuneStr(s) { t.Errorf("FullRuneStr({}) ({}) = false, want true", s, m.r) } - b1 := b[0 : len(b)-1] + b1 := b[0:len(b)-1] if utf8::FullRune(b1) { t.Errorf("FullRune({}) = true, want false", b1) } @@ -184,11 +184,11 @@ fn testDecodeRune(t: &testing::T) { if wantsize >= len(b) { wantsize = 0 } - r, size = utf8::DecodeRune(b[0 : len(b)-1]) + r, size = utf8::DecodeRune(b[0:len(b)-1]) if r != utf8::RuneError || size != wantsize { t.Errorf("DecodeRune({}) = {}, {} want {}, {}", b[0:len(b)-1], r, size, utf8::RuneError, wantsize) } - s = m.s[0 : len(m.s)-1] + s = m.s[0:len(m.s)-1] r, size = utf8::DecodeRuneStr(s) if r != utf8::RuneError || size != wantsize { t.Errorf("DecodeRuneStr({}) = {}, {} want {}, {}", s, r, size, utf8::RuneError, wantsize) @@ -209,7 +209,6 @@ fn testDecodeRune(t: &testing::T) { if r != utf8::RuneError || size != 1 { t.Errorf("DecodeRuneStr({}) = {}, {} want {}, {}", s, r, size, utf8::RuneError, 1) } - } } @@ -337,7 +336,7 @@ fn testRuneLen(t: &testing::T) { } struct validTest { - inp: str + inp: str out: bool } @@ -353,13 +352,13 @@ static validCases: []validTest = [ {str([]byte([66, 250])), false}, {str([]byte([66, 250, 67])), false}, {"a\uFFFDb", true}, - {"\xF4\x8F\xBF\xBF", true}, // U+10FFFF - {"\xF4\x90\x80\x80", false}, // U+10FFFF+1; out of range - {"\xF7\xBF\xBF\xBF", false}, // 0x1FFFFF; out of range - {"\xFB\xBF\xBF\xBF\xBF", false}, // 0x3FFFFFF; out of range - {"\xc0\x80", false}, // U+0000 encoded in two bytes: incorrect - {"\xed\xa0\x80", false}, // U+D800 high surrogate (sic) - {"\xed\xbf\xbf", false}, // U+DFFF low surrogate (sic) + {"\xF4\x8F\xBF\xBF", true}, // U+10FFFF + {"\xF4\x90\x80\x80", false}, // U+10FFFF+1; out of range + {"\xF7\xBF\xBF\xBF", false}, // 0x1FFFFF; out of range + {"\xFB\xBF\xBF\xBF\xBF", false}, // 0x3FFFFFF; out of range + {"\xc0\x80", false}, // U+0000 encoded in two bytes: incorrect + {"\xed\xa0\x80", false}, // U+D800 high surrogate (sic) + {"\xed\xbf\xbf", false}, // U+DFFF low surrogate (sic) ] #test diff --git a/std/unsafe/conv.jule b/std/unsafe/conv.jule index 003eeae82..3ba30765b 100644 --- a/std/unsafe/conv.jule +++ b/std/unsafe/conv.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use integ for std::jule::integrated +use integ "std/jule/integrated" // Returns string based on b, the parameter b means first byte of string. // The returned string uses n as length. diff --git a/tests/basic_calculator/main.jule b/tests/basic_calculator/main.jule index f33010ff4..9e30dfe39 100644 --- a/tests/basic_calculator/main.jule +++ b/tests/basic_calculator/main.jule @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use fmt for std::fmt -use conv for std::conv -use io for std::io +use "std/conv" +use "std/fmt" +use "std/io" fn readln(): str { let scanner = io::Scanner.New(io::Stdin()) diff --git a/tests/comptime/match.jule b/tests/comptime/match.jule index 72339d24b..070aa9992 100644 --- a/tests/comptime/match.jule +++ b/tests/comptime/match.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use comptime for std::comptime +use "std/comptime" fn match1() { const match comptime::TypeOf(int) { diff --git a/tests/concurrency/main.jule b/tests/concurrency/main.jule index e072cd804..8d039ae6f 100644 --- a/tests/concurrency/main.jule +++ b/tests/concurrency/main.jule @@ -2,26 +2,26 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::sync::{WaitGroup} -use std::sync::atomic::{AtomicInt, MemoryOrder} +use "std/sync" +use "std/sync/atomic" -static mut n: AtomicInt = AtomicInt.New(0) +static mut n = atomic::AtomicInt.New(0) -fn addToN(mut wg: *WaitGroup) { - unsafe defer { wg.Done() } - n.Add(1, MemoryOrder.Relaxed) +fn addToN(mut wg: &sync::WaitGroup) { + n.Add(1, atomic::MemoryOrder.Relaxed) + wg.Done() } fn main() { - let mut wg = WaitGroup{} + let mut wg = sync::WaitGroup.New() let mut j = 0 for j < 100; j++ { wg.Add(1) - co addToN(&wg) + co addToN(wg) } wg.Wait() - outln(n.Load(MemoryOrder.Relaxed)) + outln(n.Load(atomic::MemoryOrder.Relaxed)) } \ No newline at end of file diff --git a/tests/levenshtein_distance/main.jule b/tests/levenshtein_distance/main.jule index 5efa6fdbf..d19eaf3b9 100644 --- a/tests/levenshtein_distance/main.jule +++ b/tests/levenshtein_distance/main.jule @@ -25,11 +25,11 @@ fn levenshteinDistance(s1: str, s2: str): int { if len(s2) == 0 { ret len(s1) } - let v_len = len(s2) + 1 - let mut v0 = make([]int, v_len) - let mut v1 = make([]int, v_len) + let vLen = len(s2) + 1 + let mut v0 = make([]int, vLen) + let mut v1 = make([]int, vLen) let mut i = 0 - for i < v_len; i++ { + for i < vLen; i++ { v0[i] = i } i = 0 @@ -41,7 +41,7 @@ fn levenshteinDistance(s1: str, s2: str): int { if s1[i] == s2[j] { cost = 0 } - v1[j+1] = min(v1[j] + 1, v0[j+1] + 1, v0[j] + cost) + v1[j+1] = min(v1[j]+1, v0[j+1]+1, v0[j]+cost) } v0, v1 = v1, v0 } diff --git a/tests/quicksort/main.jule b/tests/quicksort/main.jule index b411c10ca..8c9e38b8d 100644 --- a/tests/quicksort/main.jule +++ b/tests/quicksort/main.jule @@ -10,11 +10,9 @@ fn quicksort(mut s: []int) { let mut i = -1 let last = s[len(s)-1] for j in s { - let mut x = &s[j] - if (unsafe { *x <= last }) { + if s[j] <= last { i++ - let mut y = &s[i] - unsafe { *x, *y = *y, *x } + s[i], s[j] = s[j], s[i] } } @@ -23,8 +21,8 @@ fn quicksort(mut s: []int) { } fn main() { - let mut my_slice = [1, 9, -2, 25, -24, 4623, 0, -1, 0xFD2] - outln(my_slice) - quicksort(my_slice) - outln(my_slice) + let mut mySlice = [1, 9, -2, 25, -24, 4623, 0, -1, 0xFD2] + outln(mySlice) + quicksort(mySlice) + outln(mySlice) } \ No newline at end of file diff --git a/tests/sleep/main.jule b/tests/sleep/main.jule index 48f1473c5..ee543f2e1 100644 --- a/tests/sleep/main.jule +++ b/tests/sleep/main.jule @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::math::rand::{Rand} -use time for std::time::{Time, Duration} +use "std/math/rand" +use "std/time" fn main() { - let mut rand = Rand.New(Time.Now().Unix()) + let mut rand = rand::Rand.New(time::Time.Now().Unix()) let mut i = 0 for i < 10; i++ { - let dur = Duration.Millisecond * rand.Nextn63(1000) + let dur = time::Duration.Millisecond * rand.Nextn63(1000) out("Sleeping for ") - out(Duration.Milliseconds(dur)) + out(time::Duration.Milliseconds(dur)) outln("ms") time::Sleep(dur) } diff --git a/tests/std/main.jule b/tests/std/main.jule index 642154fe1..939ed1004 100644 --- a/tests/std/main.jule +++ b/tests/std/main.jule @@ -1,53 +1,53 @@ // Include all standard libraries. -use std::bytes -use std::comptime -use std::conv -use std::debug -use std::encoding -use std::encoding::ascii85 -use std::encoding::base32 -use std::encoding::base64 -use std::encoding::csv -use std::encoding::json -use std::env -use std::flag -use std::fmt -use std::fs -use std::hash -use std::hash::adler32 -use std::hash::fnv -use std::fs::path -use std::io -use std::jule -use std::jule::ast -use std::jule::build -use std::jule::constant -use std::jule::importer -use std::jule::integrated -use std::jule::lex -use std::jule::parser -use std::jule::sema -use std::jule::types -use std::maps -use std::math -use std::math::big -use std::math::bits -use std::math::cmplx -use std::math::rand -use std::mem -use std::net -use std::process -use std::slices -use std::strings -use std::sync -use std::sync::atomic -use std::sys -use std::testing -use std::time -use std::unicode -use std::unicode::utf8 -use std::unicode::utf16 -use std::unsafe +use "std/bytes" +use "std/comptime" +use "std/conv" +use "std/debug" +use "std/encoding" +use "std/encoding/ascii85" +use "std/encoding/base32" +use "std/encoding/base64" +use "std/encoding/csv" +use "std/encoding/json" +use "std/env" +use "std/flag" +use "std/fmt" +use "std/fs" +use "std/fs/path" +use "std/hash" +use "std/hash/adler32" +use "std/hash/fnv" +use "std/io" +use "std/jule" +use "std/jule/ast" +use "std/jule/build" +use "std/jule/constant" +use "std/jule/importer" +use "std/jule/integrated" +use "std/jule/parser" +use "std/jule/sema" +use "std/jule/token" +use "std/jule/types" +use "std/maps" +use "std/math" +use "std/math/big" +use "std/math/bits" +use "std/math/cmplx" +use "std/math/rand" +use "std/mem" +use "std/net" +use "std/process" +use "std/slices" +use "std/strings" +use "std/sync" +use "std/sync/atomic" +use "std/sys" +use "std/testing" +use "std/time" +use "std/unicode" +use "std/unicode/utf16" +use "std/unicode/utf8" +use "std/unsafe" fn main() {} \ No newline at end of file diff --git a/tests/syntax/main.jule b/tests/syntax/main.jule index 9f344fad8..1a9e34ae1 100644 --- a/tests/syntax/main.jule +++ b/tests/syntax/main.jule @@ -1,4 +1,4 @@ -use integ for std::jule::integrated +use integ "std/jule/integrated" type TestTypeAlias: i32 @@ -120,7 +120,9 @@ fn testIter() { _ = index } - for { break } + for { + break + } let mut a = 0 for a <= 3; a++ { diff --git a/tests/traits/main.jule b/tests/traits/main.jule index 1df17eb02..6f4d7623c 100644 --- a/tests/traits/main.jule +++ b/tests/traits/main.jule @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD 3-Clause // license that can be found in the LICENSE file. -use std::math::{Pi} +use "std/math" trait Shape { fn area(self): f32 @@ -25,7 +25,7 @@ struct Circle { impl Shape for Circle { fn area(self): f32 { - ret Pi * self.r * self.r + ret math::Pi * self.r * self.r } }