AfxFilenameOriginalCase

Started by Paul Squires, January 05, 2026, 06:23:29 PM

Previous topic - Next topic

Paul Squires

Hi José,

I am sharing a new function (code below) that I wrote the other day. There are times when you have a full path filename in some type of letter casing but you want to interact with that filename in its original casing per the way it is stored in Windows.

For example, I am integrating the GDB Debugger into Tiko and GDB returns filenames back to Tiko in UPPERCASE format. Sure, I could use that uppercase file and display it in uppercase but visually it looks much more pleasing for the filename to display within the Tiko Editor using the original case.

A filename like:
C:\DEV\TIKO_EDITOR_DEBUGGER\DEBUG-EXAMPLE\TESTFILE2.BAS

Gets converted to:
C:\dev\tiko_editor_debugger\Debug-Example\TestFile2.bas

This code might be interesting to add to AfxNova if you also find it worthwhile.

' ========================================================================================
' Get the original case filename as stored by Windows
' ========================================================================================
function AfxFilenameOriginalCase( byval filename as DWSTRING ) as DWSTRING
    dim as long bufSize = 1024
    dim as DWSTRING buffer = wspace(bufSize \ 2)

    dim as HANDLE hfile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, _
                                null, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, null)

    if hfile = INVALID_HANDLE_VALUE then exit function

    dim as DWORD result = GetFinalPathNameByHandleW( hfile, *buffer, bufSize, FILE_NAME_NORMALIZED )

    if (result > 0) andalso (result < bufSize) then
        ' Good data returned but still need to remove the mapping characters
        if left(buffer, 4) = "\\?\" then buffer = mid(buffer, 5)
    else
        ' error: could not retrieve path.
    end if

    ' clean up
    CloseHandle(hfile)
   
    function = buffer
end function
Paul Squires
PlanetSquires Software

José Roca

Hi Paul,

I didn't forget about the function you proposed earlier.
The reason I didn't implement it immediately is that something important was missing, and I needed to study the official documentation for GetFinalPathNameByHandleW first.

According to Microsoft's documentation , the function's return value is the length of the string in TCHARs, excluding the terminating null character. This detail affects how the buffer must be allocated and how the result must be trimmed. Without understanding this behavior precisely, the function could return incorrect or partially truncated paths, especially when dealing with long filenames or UNC paths.

Once I reviewed the documentation carefully, I was able to implement a correct and robust version:

- dynamic buffer resizing based on the exact size required

- proper handling of the \\?\ and \\?\UNC\ prefixes

- correct trimming of the returned string

- support for both files and directories

and a variant that accepts a HANDLE directly

So the delay wasn't because I forgot your suggestion — I simply needed to confirm how the API behaves internally before finalizing the implementation.

Thanks again for the original idea. It was a good starting point, and now the function works reliably in all cases.

I have added them to fbxWin.inc, using USTRING and DEFER.

' ========================================================================================
' Returns the original-case filename as stored by Windows.
' Uses GetFinalPathNameByHandleW with dynamic buffer, UNC handling,
' directory support, and automatic cleanup via DEFER.
' ========================================================================================
FUNCTION fbxGetFilenameOriginalCase OVERLOAD (BYREF wszFileName AS WSTRING) AS USTRING
   DIM INITIAL_SIZE AS LONG = 1024
   DIM hFile AS HANDLE
   DIM dwNeeded AS DWORD
   DIM dwFlags AS DWORD = FILE_NAME_OPENED
   DIM ustrResult AS USTRING = WSPACE(INITIAL_SIZE \ 2)
   ' Open file or directory
   hFile = CreateFileW(wszFileName, GENERIC_READ, _
                       FILE_SHARE_READ OR FILE_SHARE_WRITE OR FILE_SHARE_DELETE, _
                       NULL, OPEN_EXISTING, _
                       FILE_ATTRIBUTE_NORMAL OR FILE_FLAG_BACKUP_SEMANTICS, _
                       NULL)
   IF hFile = INVALID_HANDLE_VALUE THEN RETURN ""
   ' Automatic cleanup
   DEFER CloseHandle(hFile)
   ' First call: get required size
   dwNeeded = GetFinalPathNameByHandleW(hFile, STRPTR(ustrResult), INITIAL_SIZE, dwFlags)
   IF dwNeeded = 0 THEN RETURN ""
   ' Resize buffer if needed
   IF dwNeeded >= INITIAL_SIZE THEN
      ustrResult = WSPACE(dwNeeded + 1)
      dwNeeded = GetFinalPathNameByHandleW(hFile, STRPTR(ustrResult), dwNeeded + 1, dwFlags)
      IF dwNeeded = 0 THEN RETURN ""
   END IF
   ' Trim to actual length (dwNeeded does not include the null terminator)
   ustrResult = LEFT(ustrResult, dwNeeded)
   ' Remove \\?\ prefix
   IF LEFT(ustrResult, 4) = $"\\?\" THEN
      ustrResult = MID(ustrResult, 5)
   ELSEIF LEFT(ustrResult, 7) = $"\\?\UNC\" THEN
      ustrResult = $"\\" & MID(ustrResult, 7)
   END IF
   RETURN ustrResult
END FUNCTION
' ========================================================================================
' ========================================================================================
' Returns the original-case filename associated with a HANDLE.
' The HANDLE must refer to a file or directory opened with sufficient access rights.
' ========================================================================================
FUNCTION fbxGetFilenameOriginalCaseFromHandle OVERLOAD (BYVAL hFile AS HANDLE) AS USTRING
   DIM INITIAL_SIZE AS LONG = 1024
   DIM dwNeeded    AS DWORD
   DIM dwFlags     AS DWORD = FILE_NAME_OPENED
   DIM ustrResult  AS USTRING = WSPACE(INITIAL_SIZE \ 2)
   ' Validate handle
   IF hFile = INVALID_HANDLE_VALUE OR hFile = NULL THEN RETURN ""
   ' First call: get required size
   dwNeeded = GetFinalPathNameByHandleW(hFile, STRPTR(ustrResult), INITIAL_SIZE, dwFlags)
   IF dwNeeded = 0 THEN RETURN ""
   ' Resize buffer if needed
   IF dwNeeded >= INITIAL_SIZE THEN
      ' dwNeeded = number of characters without the terminating null
      ustrResult = WSPACE(dwNeeded + 1)
      dwNeeded = GetFinalPathNameByHandleW(hFile, STRPTR(ustrResult), dwNeeded + 1, dwFlags)
      IF dwNeeded = 0 THEN RETURN ""
   END IF
   ' Trim to actual length (dwNeeded does not include the null terminator)
   ustrResult = LEFT(ustrResult, dwNeeded)
   ' Remove \\?\ prefix
   IF LEFT(ustrResult, 4) = $"\\?\" THEN
      ustrResult = MID(ustrResult, 5)
   ELSEIF LEFT(ustrResult, 7) = $"\\?\UNC\" THEN
      ustrResult = $"\\" & MID(ustrResult, 7)
   END IF
   RETURN ustrResult
END FUNCTION
' ========================================================================================

Paul Squires

Excellent - thanks José, appreciate it!
Paul Squires
PlanetSquires Software

Pierre Bellisle

Hey guys !

IF LEFT(ustrResult, 4) = $"\\?\" THEN
  '
ELSEIF LEFT(ustrResult, 7) = $"\\?\UNC\" THEN
  'This part will never be reached because the first [IF] will be triggered
END IF

José Roca

#4
Thanks, Pierre—long time no see!

This feature was included in fbx, a framework for FBC-Modern, but it no longer exists because that project eventually evolved into tiko-lang.

https://tiko-lang.net/

Pierre Bellisle

¡Hola, José!

¡Hace mucho que no nos vemos, de verdad! (Long time no see indeed!)

In fact, I've end up here reading Tiko stuff...

Seems Paul dit it again!
And having you as a accomplice is nothing but good news.

I guess I will read a little more about the new kid in town,
I already saw many great things, 
not to say about the LLVM choice, which is a pretty nice one in my humble opinion.

cu

José Roca

#6
There is a lot to read: thousands of pages and two books. Some of the new features have already become indispensable to me.

My AfxNova framework for FreeBasic was very large because it sought to compensate for FreeBasic's shortcomings regarding Unicode, math, string manipulation, file handling, etc.

All of that is now incorporated into tiko-lang, so my library for Windows will focus on APIs that exist only on Windows, e.g. GDI+, RichEdit, WebView2, Direct2D, COM, etc.

I hope this can be useful for programmers like me who work exclusively with Windows.


Pierre Bellisle

#7
To be honest, as you may already know, my fondness for FB wasen't eternal.
Too many of this, not enough of that...
Pre-looking at Tiko compiler, I think that many of the little things I personnally have trouble with in FB are things of the past. Not to say that the evolution of the FB language is quite slow, exepting for the effort of two certain guys, of course...

This fresh wind is welcome.

The dynamic strings managment looks great, I've always thought that this was at the eart of any BASIC language. It dosen't look like my beloved bstr are there, look alike Ustring is another things that I will have to check. I guess thinking multi platform have some exigences or maybe there are other advantage that I'm not aware of. More stuff to think about...
I've already seen https://www.planetsquires.com/protect/forum/index.php?topic=4881.0

The embedded functions list is impressive. Like in many language, some looks like simple api call but they are well choosen and I'm sure majority will find usefull, it may act also as a memory refresher of what is avaiable for api lovers.

For your framework, if I understand well, I do not have to look anywhere else than in Tiko folder. Simple is beautiful.

If I may ask, you know how curious I am, as an apetizer, can you tell some of new features that are now indispensable to you?

José Roca

Two of them are defer and the tuples. The benefits of using them is immediate, so I already have used them in my library. And, of course, one of the biggest advantages is to have a native Unicode string.

Please, also notice that we can Overload api functions. You can use the api function directly:

DIM rc AS RECT
GetWindowRect(hWin, @rc)

or use a tuple like this


' ========================================================================================
' Usage example:
' var(l, t, r, b) = GetWindowRect(hButton)
' IF GetLastError = 1 THEN print l, t, r, b
' ========================================================================================
PUBLIC FUNCTION GetWindowRect OVERLOAD (BYVAL hWin AS HWND) AS (LONG, LONG, LONG, LONG)
   DIM rc AS RECT
   SetLastError(GetWindowRect(hWin, @rc))
   RETURN (rc.left, rc.top, rc.right, rc.bottom)
END FUNCTION
' ========================================================================================

We also can return arrays as the result of a function and Result or Option.

`defer` ensures that an action is executed when the function finishes, and in the correct reverse order. This avoids the need to manually release existing objects if errors occur. For example:

   ' // Create a graphics object from the device context
   DIM graphics AS GpGraphics PTR
   status = GdipCreateFromHDC(hdc, @graphics)
   IF graphics = NULL THEN EXIT SUB
   defer GdipDeleteGraphics(graphics)

   ' // Create an AdjustableArrowCap that is filled.
   DIM arrowCapStart AS GpAdjustableArrowCap PTR
   status = GdipCreateAdjustableArrowCap(10, 10, TRUE, @arrowCapStart)
   IF arrowCapStart = NULL THEN EXIT SUB
   defer GdipDeleteCustomLineCap(arrowCapStart)

If GdipCreateAdjustableArrowCap fails, we can simply use EXIT SUB instead of

   IF arrowCapStart = NULL THEN
      GdipDeleteGraphics(graphics)
      EXIT SUB
   END IF

   DIM arrowCapEnd AS GpAdjustableArrowCap PTR
   status = GdipCreateAdjustableArrowCap(15, 15, FALSE, @arrowCapEnd)
   IF arrowCapEnd = NULL THEN
      GdipDeleteCustomLineCap(arrowCapStart)
      GdipDeleteGraphics(graphics)
      EXIT SUB
   END IF

I have been conservative when adapting code coming from AfxNova because I didn't want to introduce bugs in code that was already working, but I will use the new features in new wrappers.

Pierre Bellisle

Indeed, defer and tuples looks great.
I would have loved to have OverLoad in PB time.

What jump out at me is that the spirit of this "BASIC" or Tyco compiler if you prefer is so clean, when Paul say "Code you can read." he is quite right...

It could be a teacher's pet for many coder who like the approach...

José Roca

The best way to explore the new features is through the book "Tiko by Example".

https://tiko-lang.net/by-example/

Tiko has adopted features from modern languages like Rust and Go, while retaining the readability of BASIC.

Paul Squires

Quote from: José Roca on November 19, 2026, 08:21:39 AMTiko has adopted features from modern languages like Rust and Go, while retaining the readability of BASIC.

Here is what I posted over in the FreeBASIC forum that reinforces José's above quote.

A major design goal of tiko was to add modern features that FreeBASIC does not have — the features people would naturally turn to in Rust, C++, Zig and Odin. For many years, I envied some of the features only available outside of FreeBASIC so with tiko I ensured that I would have all the tools that I always wished I had without having to relearn a brand new foreign language.

The following is a small list of those features. Everything is coded in a style that still reads like the BASIC we know. You can mix all of these features freely with your existing #lang "fb" code in the same program.

  • Generics with type inference and interface constraints — Rust generics and trait bounds, C++ templates and concepts
  • Lambdas and closures with explicit capture lists — C++ [=] / [&], Rust closures
  • Tuples, named elements and destructuring — Rust tuples, C++ structured bindings, Odin and Zig multiple returns
  • defer — Zig, Odin, Go
  • Result and Optional, checked / saturating / wrapping arithmetic — Rust, C++23 std::expected, Zig error unions
  • Iterators and lazy sequences for for each — Rust's Iterator, C++ range-for
  • Interfaces with dynamic or static dispatch — Rust traits and dyn, Go interfaces
  • Slices with compile-time borrow checking — Rust &str, C++ string_view, Zig and Odin slices
  • SharedPtr and WeakPtr — C++ shared_ptr / weak_ptr, Rust Rc / Weak
  • spawn, channels and select — Go, Rust's channels
  • #cinclude: use a C header directly — Zig's @cImport
1. Generics

The generics example is in the earlier announcement post: Array( of Stock ) and Map( of ustring, ustring ). A generic can also state what it needs from T, as a Rust trait bound or a C++20 concept does: of T as IShape. That is in section 7.

2. Lambdas and closures

A lambda is a function or sub with no name, written where it is used. A closure lists the variables it captures in square brackets, and, as in C++, says for each one how it is held: byval takes a copy when the closure is made, byref works on the caller's own variable. Leaving the mode out is a compile error (TKO0413), so nobody has to guess. A generic parameter F accepts any callable: a procedure, a lambda or a closure.

'' A higher-order generic: F is any callable -- a procedure, a lambda
'' or a closure.
function CountIf( of T, F )( items() as T, byref test as F ) as int32
    dim as int32 n = 0
    for each x in items
        if test( x ) then n += 1
    next
    return n
end function

dim temps( 0 to 6 ) as int32 = { 12, 25, 31, 18, 29, 35, 9 }

'' A lambda written right at the call.
print "days over 30:"; CountIf( temps(), function( byval t as int32 ) as boolean
    return t > 30
end function )

'' A closure. The capture list says how each variable is held, as in
'' C++: byval copies it now, byref uses the caller's own variable.
dim as int32 limit = 20
dim as int32 checked = 0
var warm = function[ byval limit, byref checked ]( byval t as int32 ) as boolean
    checked += 1
    return t > limit
end function

limit = 99                       '' too late: warm already copied 20
print "days over 20:"; CountIf( temps(), warm )
print "the closure ran"; checked; " times"

days over 30: 2
days over 20: 4
the closure ran 7 times

3. Tuples and destructuring

A function can return several values at once, with names, and no byref out-parameters. The caller takes the tuple apart with var ( a, b, c ) =, or keeps it whole and uses the names. Tuple assignment reads the whole right side before it writes anything, so a swap needs no temporary.

'' Several results, with names, and no byref out-parameters.
function Stats( values() as float64 ) _
    as ( lo as float64, hi as float64, mean as float64 )
    dim as float64 lo = values( 0 ), hi = lo, sum = 0
    for each v in values
        if v < lo then lo = v
        if v > hi then hi = v
        sum += v
    next
    return ( lo, hi, sum / ( ubound( values ) + 1 ) )
end function

dim prices( 0 to 4 ) as float64 = { 101.5, 99.25, 104.0, 98.75, 102.5 }

'' Take the tuple apart into new variables...
var ( lo, hi, mean ) = Stats( prices() )
print "low"; lo; "  high"; hi; "  mean"; mean

'' ...or keep it whole and use the names.
var s = Stats( prices() )
print "range:"; s.hi - s.lo

'' Tuple assignment reads the whole right side first, so a swap
'' (or a Fibonacci step) needs no temporary.
dim as int64 a = 0, b = 1
for i as int32 = 1 to 90
    ( a, b ) = ( b, a + b )
next
print "fib(90) ="; a

low 98.75  high 104  mean 101.2
range: 5.25
fib(90) = 2880067194370816120

for each takes tuples apart too: for each (key, value) in map.Pairs( ).

4. defer

Straight from Zig and Odin (and Go): defer runs a statement when the enclosing block is left, by whatever path — the end of the block, return, exit sub — in reverse order. The cleanup sits on the line after the thing it cleans up, and an early return can never skip it.

'' defer runs a statement when the enclosing block is left, by any path,
'' last-in first-out. The cleanup sits next to what it cleans up.
function Transfer( byval amount as int32 ) as boolean
    print "  lock accounts"
    defer print "  unlock accounts"

    print "  begin transaction"
    defer print "  end transaction"

    if amount > 1000 then
        print "  refused: over the limit"
        return false                     '' both defers still run
    end if
    print "  moved"; amount
    return true
end function

print "transfer 250:"
Transfer( 250 )
print "transfer 5000:"
Transfer( 5000 )

transfer 250:
  lock accounts
  begin transaction
  moved 250
  end transaction
  unlock accounts
transfer 5000:
  lock accounts
  begin transaction
  refused: over the limit
  end transaction
  unlock accounts

5. Errors as values: Result and Optional

Result( of T, E ) holds either a value or the reason there is none, as Rust's Result, C++23's std::expected and Zig's error unions do. The signature says the function can fail, the caller decides what a failure means, and nothing is thrown. Optional( of T ) is a value that may be absent.

The numeric library uses the same idea for integer overflow, with the three choices Rust and Zig give you: checked (an empty Optional instead of a wrong number), saturating and wrapping.

#import "std/outcome"
#import "std/numeric"

type PortResult as outcome.Result( of int32, ustring )

'' Errors are values: the signature says this can fail, and why.
function ParsePort( byref text as ustring ) as PortResult
    var port = valint( text )
    if str( port ) <> text orelse port < 1 orelse port > 65535 then
        return outcome.Fail( of int32, ustring )( "bad port '" & text & "'" )
    end if
    return outcome.Ok( of int32, ustring )( port )
end function

dim inputs( 0 to 2 ) as ustring = { "8080", "http", "70000" }
for each t in inputs
    var r = ParsePort( t )
    if r.IsOk( ) then
        print "port"; r.Value( )
    else
        print "error: "; r.Failure( )
    end if
next

'' Overflow on your terms: checked (an Optional), saturating, wrapping.
dim as int32 top = 2147483647
print "checked has a value? "; numeric.AddChecked( top, 1 ).HasValue( )
print "saturating:"; numeric.AddSaturating( top, 1 )
print "wrapping:  "; numeric.AddWrapping( top, 1 )

port 8080
error: bad port 'http'
error: bad port '70000'
checked has a value? false
saturating: 2147483647
wrapping:  -2147483648

Paul Squires
PlanetSquires Software

Paul Squires

6. Iterators and lazy sequences

for each walks arrays, strings and every container in the standard library, and it walks your own types too. A type is iterable when it has a GetIterator( ) method, and the iterator has IsValid( ), Value( ) and MoveNext( ). There is nothing to inherit and no virtual call: the compiler calls those methods directly, much as C++'s range-for calls begin and end.

An iterator does not have to walk anything stored. This one computes the Fibonacci sequence as the loop asks for it, for ever, and exit for decides where it ends:

'' Any type is iterable: GetIterator( ), plus IsValid / Value / MoveNext.
'' No interface to inherit, no virtual calls: for each calls them directly.
type FibIterator
    as uint64 a, b
    declare function IsValid( ) as boolean
    declare function Value( ) as uint64
    declare sub MoveNext( )
end type

function FibIterator.IsValid( ) as boolean
    return true                       '' an endless sequence
end function

function FibIterator.Value( ) as uint64
    return a
end function

sub FibIterator.MoveNext( )
    ( a, b ) = ( b, a + b )
end sub

type Fibonacci
    as uint64 first, second
    declare function GetIterator( ) as FibIterator
end type

function Fibonacci.GetIterator( ) as FibIterator
    return type( first, second )
end function

'' Lazy: each number is computed only when the loop asks for it.
dim fib as Fibonacci = ( 0, 1 )
for each n in fib
    if n > 1000 then exit for
    print n; " ";
next
print

dim as int32 count = 0
for each n in fib
    count += 1
    if n >= 100000000000000 then
        print "the first with 15 digits is number"; count; ": "; n
        exit for
    end if
next

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
the first with 15 digits is number 70: 117669030460994

for each byref x in items changes the elements in place.

7. Interfaces: dynamic and static dispatch

An interface is a contract with no data and no code. Any type takes it on with implements — a plain type included, with no base class and no table pointer inside it. You then choose the dispatch, as in Rust:
  • Dynamic: a parameter typed IShape accepts any implementing object. An interface value is a 16-byte reference that does not own its object, like Rust's &dyn Trait or a Go interface.
  • Static: a generic constrained with of T as IShape, like a Rust trait bound or a C++20 concept. The constraint is checked where the generic is used, and the calls in its body are direct.
'' An interface is a contract: no data, no code.
interface IShape
    function Name( ) as ustring
    function Area( ) as float64
end interface

'' Plain types take it on: no base class, no vtable inside the type.
type Circle
    implements IShape
    declare function Name( ) as ustring implements IShape.Name
    declare function Area( ) as float64 implements IShape.Area
    as float64 r
end type

function Circle.Name( ) as ustring
    return "circle"
end function

function Circle.Area( ) as float64
    return 3.141592653589793 * r * r
end function

type Rect
    implements IShape
    declare function Name( ) as ustring implements IShape.Name
    declare function Area( ) as float64 implements IShape.Area
    as float64 w, h
end type

function Rect.Name( ) as ustring
    return "rect"
end function

function Rect.Area( ) as float64
    return w * h
end function

'' Dynamic dispatch: written once, against the contract only.
sub Report( byval s as IShape )
    print s.Name( ); " area"; s.Area( )
end sub

'' Static dispatch: a constrained generic. T must implement IShape,
'' checked where it is used; the calls in the body are direct.
function TotalArea( of T as IShape )( items() as T ) as float64
    dim as float64 sum = 0
    for each x in items
        sum += x.Area( )
    next
    return sum
end function

dim c as Circle = ( 2 )
dim r as Rect = ( 3, 4 )
Report( c )
Report( r )

dim tiles( 0 to 2 ) as Rect = { ( 1, 2 ), ( 3, 4 ), ( 5, 6 ) }
print "total area of the tiles:"; TotalArea( tiles() )
print "an IShape value is"; sizeof( IShape ); " bytes; a Rect is"; sizeof( Rect )

circle area 12.56637061435917
rect area 12
total area of the tiles: 44
an IShape value is 16 bytes; a Rect is 16

A Rect is still exactly its two doubles. Pass an int32 array to TotalArea and the compiler refuses it at the call:

error TKO1022: type argument 'int32' does not implement 'ishape', which 'totalarea( of t )' requires
A type may implement any number of interfaces, interfaces can themselves be generic (IComparable( of T )), and trycast asks an object whether it implements one.

8. Slices, with borrow checking

s[lo to hi] names part of a string where it already is: no copy, no allocation — Rust's &str, C++'s string_view, a slice in Zig or Odin. Writing through a slice writes into the string it came from.

#import "std/strings"

dim as ustring csv = "AAPL,228.52,40"

'' s[lo to hi] names part of a string where it already is:
'' no copy, no allocation.
dim as uslice symbol = csv[0 to 3]
print "symbol: "; symbol; ", length"; len( symbol )

'' SplitSlices hands out views one at a time; nothing is allocated.
for each field as const uslice in strings.SplitSlices( csv[0 to len( csv ) - 1], "," )
    print "  ["; field; "]"
next

'' Writing through a slice writes into the string it came from.
symbol[0] = asc( "a" )
print csv

symbol: AAPL, length 4
  [AAPL]
  [228.52]
  [40]
aAPL,228.52,40

The interesting part is what tiko refuses. A string_view in C++, or a slice in Zig or Odin, will happily outlive the text it points into. tiko tracks where each slice came from, Rust-style, and while a slice is still in use the string it borrows from cannot be changed in a way that could move its text:

dim as ustring name_ = "Ada"
dim as const uslice initial = name_[0 to 0]

'' Appending may move the text, leaving initial pointing at freed memory.
name_ &= " Lovelace"
print initial

08b-slicelock.tiko(5,1): error TKO1062: 'name_' cannot be changed while slice 'initial' borrows from it (last used at line 6)
     |
   5 | name_ &= " Lovelace"
     | ^

Move the print above the &= and it compiles: the borrow ends at the slice's last use. A slice also cannot be stored anywhere that could outlive its text (a shared or static, an array or container element), and a function cannot return a slice of its own local copy. The compiler checks one procedure at a time; when another procedure changes the string, -exx catches it at run time.

9. Shared ownership: SharedPtr and WeakPtr

Most tiko code needs no smart pointer: strings and containers free themselves at the end of their scope, destructors run, and defer covers the rest. For an object with several owners there is SharedPtr( of T ), which counts its owners, and WeakPtr( of T ), which observes without owning and breaks the reference cycles that counting alone cannot — the same pair as C++'s shared_ptr / weak_ptr and Rust's Rc / Weak.

#import "std/memory"

type Node
    as ustring name
    as memory.SharedPtr( of Node ) child     '' owns downward
    as memory.WeakPtr( of Node ) parent      '' observes upward
    declare destructor( )
end type

destructor Node( )
    print "  freed "; name
end destructor

scope
    var root = memory.MakeShared( of Node )( )
    root->name = "root"
    var leaf = memory.MakeShared( of Node )( )
    leaf->name = "leaf"

    root->child = leaf                 '' leaf now has two owners
    leaf->parent = root                '' a weak link: not an owner

    print "leaf owners:"; leaf.UseCount( ); ", root owners:"; root.UseCount( )
    var up = leaf->parent.Lock( )      '' an owner for as long as we hold it
    print "leaf's parent is "; up->name
end scope                              '' the counts reach zero: both freed
print "scope ended"

leaf owners: 2, root owners: 1
leaf's parent is root
  freed root
  freed leaf
scope ended

Make the parent link a SharedPtr too and neither destructor ever runs: the two nodes keep each other alive. That is exactly what WeakPtr is for.

10. spawn, channels and select

spawn Proc( args ) runs a procedure concurrently, and typed channels carry values between them. A channel can be handed out as only its sending end (SendChan) or only its receiving end (RecvChan), so each stage of a pipeline can do only what it should — Go's chan<- / <-chan, Rust's Sender / Receiver. Closing a channel ends every for each over it, and select channel waits on several channels at once, with an optional time-out.

#import "std/tasks"
#cmdline "-mt"

'' Each stage holds only the end of a channel it needs:
'' a SendChan can only send, a RecvChan can only receive.
sub Produce( byval upTo as int32, byval out_ as tasks.SendChan( of int32 ) )
    for i as int32 = 1 to upTo
        out_.Send( i )
    next
    out_.Close( )
end sub

sub Square( byval in_ as tasks.RecvChan( of int32 ), _
            byval out_ as tasks.SendChan( of int32 ) )
    dim as int32 v
    do while in_.Receive( v )         '' false once in_ is closed and empty
        out_.Send( v * v )
    loop
    out_.Close( )
end sub

var numbers = tasks.Channel( of int32 )( 0 )   '' unbuffered: a handover
var squares = tasks.Channel( of int32 )( 0 )
spawn Produce( 8, numbers )
spawn Square( numbers, squares )

dim as int32 total = 0
for each v in squares                 '' ends when Square closes it
    print v;
    total += v
next
print
print "sum of squares:"; total

'' select channel waits on several channels at once, or for a time-out.
var quiet = tasks.Channel( of int32 )( 1 )
dim as int32 got
select channel
    case receive got from quiet : print "got"; got
    case timeout 50             : print "nothing within 50 ms"
end select

1 4 9 16 25 36 49 64
sum of squares: 204
nothing within 50 ms

std/tasks also has a WaitGroup for worker pools, and because a closed channel is always ready to receive, closing one is a cancellation signal that any select can listen for.

11. #cinclude: use a C header as it is

Like Zig's @cImport, #cinclude reads a C library's own header through libclang and makes tiko declarations from it — functions, structs, constants. There is no binding to write or to keep up to date:

'' #cinclude reads a C header through libclang: no binding to write.
#cinclude once "stdlib.h"
#cinclude once "string.h"

function Compare cdecl( byval a as const any ptr, byval b as const any ptr ) as int32
    return *cptr( const int32 ptr, a ) - *cptr( const int32 ptr, b )
end function

dim nums( 0 to 5 ) as int32 = { 42, 7, 19, 3, 88, 25 }
qsort( @nums( 0 ), 6, sizeof( int32 ), @Compare )    '' C's own qsort
for each n in nums
    print n;
next
print
print "strlen: "; strlen( "tiko" )
dim as div_t d = div( 47, 10 )          '' a C struct, straight from the header
print "div( 47, 10 ) ="; d.quot; " remainder"; d.rem_

3 7 19 25 42 88
strlen: 4
div( 47, 10 ) = 4 remainder 7

(C's field rem is a tiko keyword, so it arrives as rem_.)

Prefer a binding you can read, edit and check in? tiko c2t header.h -o header.ti converts a C header into a tiko header once, much as fbfrog does for FreeBASIC: constants, structs and function declarations come out as plain tiko source, and anything it cannot translate is marked C2T-TODO for you to finish by hand.

And more
  • Modules and packages: #import "std/strings" instead of a header, with visibility, re-exports and packages of your own.
  • Partial types: one type written in several blocks, or several files.
  • Auto-properties and property blocks: get, private set, properties with any number of indices, static and namespace properties.
  • ustring, the fixed-width type names (int8 to float64), block strings (""") and collection initialisers.
  • Generic containers: Array, Map, Set, OrderedMap, OrderedSet, LinkedList, Deque, PriorityQueue and BitSet, with your own types as keys.

tiko is a very deep language. It is not simply FreeBASIC with some sugar on top.

Paul Squires
PlanetSquires Software