r/Compilers • • Oct 20 '26

Mixed of FUNCTIONAL BASIC and CLIPPER 5.3 into a C99 Compiler

I always loved BASIC and CLIPPER 5.3, so I started from an old and never finished BASIC compiler and I asked the AI to improve it adding advanced functions and CLIPPER 5.3 commands, including code-blocks, macro, runtime eval, SAY/GET/READ subsystem. Currently the compiler works on MacOS and Linux. Window version by Visual C++ will come as soon as I will have a laptop with windows installed. I am trying Mingw for windows.

This is an example using macros, eval and code-blocks. It shows also functions passed as parameters of other functions and Sub Main as entry-point.

'FILE: Clipper/ClipperMacroEvalBlocksExtreme.bas

IMPORT ARRAYS

GLOBAL TaxRate AS DOUBLE
GLOBAL cName AS STRING

FUNCTION MkInc() AS FUNCTION(x) AS DOUBLE
    RETURN { |x| RETURN x + 1 }
END FUNCTION

FUNCTION ApplyFn(b AS FUNCTION(x) AS DOUBLE, v AS DOUBLE) AS DOUBLE
    RETURN EVAL(b, v)
END FUNCTION

SUB Main()

    TaxRate = 0.22
    PRINT "=== Clipper macro/EVAL/blocks (extreme) ==="

    'Macro ESPRESSIONE compilata (aritmetica + globale)
    DIM cPrice AS STRING = "100"
    DIM cNet AS STRING = "VAL(cPrice) * (1 + TaxRate)"
    PRINT "net="; &(cNet)                       ' 122

    'Macro VARIABILE: il nome della variabile e' nei dati
    DIM which AS STRING = "TaxRate"
    PRINT "tax="; &which                        ' 0.22

    'Macro COSTANTE che produce un CODE BLOCK (compilato una volta)
    DIM bGross = &("{ |p| RETURN p * (1 + TaxRate) }")
    PRINT "gross(100)="; EVAL(bGross, 100)      ' 122
    PRINT "gross(200)="; EVAL(bGross, 200)      ' 244

    'Macro su VARIABILE con block LETTERALE (espansione compile-time)
    DIM cBlockDef AS STRING = "{ |p| RETURN p * (1 + TaxRate) }"
    DIM bVar = &(cBlockDef)
    PRINT "vargross(150)="; EVAL(bVar, 150)     ' 183

    'Code block letterale + EVAL multi-argomento
    DIM bArea = { |w, h| RETURN w * h }
    PRINT "area="; EVAL(bArea, 6, 7)            ' 42

    'Block con concat: risultato stringa + param usato solo in concat
    DIM bBang = { |s| RETURN UPPER(s) + "!" }
    PRINT "bang="; EVAL(bBang, "x")             ' X!
    DIM bRaw = { |s| RETURN s + "!" }
    PRINT "raw="; EVAL(bRaw, "x")               ' x!

    'Block applicato a tutti gli elementi di un array (AEVAL: elemento, indice)
    DIM prices = {100, 200, 300}
    AEVAL prices, { |v, i| PRINT "  gross["; i; "]="; v * (1 + TaxRate) }   ' 122 244 366

    'Nested Macros
    DIM cThree AS STRING = "deep!"
    DIM cTwo AS STRING = "cThree"
    DIM cOne AS STRING = "&cTwo"
    PRINT "nested="; &cOne                       ' deep!
    'EVAL stringa (GMBasic) come COMANDO + text substitution (globale)
    EVAL("TaxRate = 0.10")
    PRINT "tax2="; &("TaxRate")                  ' 0.1
    cName = "world"
    PRINT "subst=Hello &cName!"     ' Hello world!  (globale espanso)

    'EVAL con block INLINE + block restituito da funzione
    PRINT "inline="; EVAL({ |s| RETURN UPPER(s) + "!" }, "x")   ' X!
    PRINT "fromfn="; EVAL(MkInc(), 5)                           ' 6
    DIM bm = MkInc()
    PRINT "infvar="; EVAL(bm, 5)                                ' 6
    EVAL({ |s| PRINT "stmt="; s }, "y")                         ' stmt=y

    'Closure: EVAL annidato + function-value catturato + param FUNCTION
    PRINT "nested="; EVAL({ |x| RETURN EVAL({ |y| RETURN y + 1 }, x) }, 5)  ' 6
    DIM inner = { |y| RETURN y + 1 }
    DIM outer = { |x| RETURN EVAL(inner, x) }
    PRINT "capt="; EVAL(outer, 5)                               ' 6
    PRINT "param="; ApplyFn({ |z| RETURN z * 2 }, 21)           ' 42
    PRINT "Clipper macro/EVAL/blocks: fatto."

END SUB

The compiler supports graphics by SDL, Vulkan, Game Loop (thousands of fluid sprites), TUI, Windows Manager, DBF files with memo field (DBIII/DBIV/Clipper/FoxPro), TBROWSE, ISAM, RDD system, SQL (SQLite/DuckDB integrated), REPL, Package Manager (like cargo/pip/modules), and more.

The compiler supports also numbered lines, GOTO, GOSUB, ON ERROR, ON KEY, etc.

This an attempt to bring old clipper/basic programmers into a modern world, saving their old code.

Will you try it if will be made open source and what do you think about it?

3 Upvotes

7 comments sorted by

1

u/jcastroarnaud Oct 21 '26

Cursed! Thank you for the weirdness.

Can I use lowercase keywords?
The difference from "function... end function" to "{ | | .. }" is a bit jarring. I would use the longhand "function" or "sub" everywhere, even if longer to type.
Are argument types on functions/subs optional? If so, what is the default type?
What are the exact semantics of "&", "&()" and "eval"? What happens if a uncompilable string is passed to any of these to evaluate?
For higher-order functions, consider allowing the use of parentheses to group types. For instance: "function map( fn: (function(element: Any) as Any), list: Array of Any) ) as (Array of Any)".
Do you have closures and lexical scope? Did you test them?

1

u/gmbasic Oct 21 '26

Hi, thanks for your feedback. The syntax { | | .. } is for clipper's code blocks compatibility. Yes, closures are fully supported. Additional examples, currently compiling:

FN() is an alias for FUNCTION()

LET Triplica = FN(x AS INTEGER) AS INTEGER => x * 3
PRINT "Lambda 'Triplica' creata con sintassi =>"
PRINT "Triplica(10) -> "; Triplica(10)

Lambda with arguments

    DIM Numeri() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    PRINT "Array originale: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"
    
    ' AMAP: Applica una funzione a ogni elemento (Proiezione).
    ' Qui usiamo una lambda per elevare al quadrato.
    DIM Quadrati() = AMAP(Numeri, FN(n AS INTEGER) AS INTEGER => n * n)
    PRINT "Array al quadrato (AMAP): ";
    AEVAL Quadrati, SUB(x AS INTEGER) { PRINT x; " "; } : PRINT

    ' AFILTER: Seleziona gli elementi che soddisfano un predicato.
    ' Qui usiamo una lambda per selezionare i numeri pari.
    DIM Pari() = AFILTER(Numeri, FN(n AS INTEGER) AS INTEGER => (n MOD 2) = 0)
    PRINT "Numeri pari (AFILTER): ";
    AEVAL Pari, SUB(x AS INTEGER) { PRINT x; " "; } : PRINT
    
    ' AREDUCE: Aggrega gli elementi in un singolo valore.
    ' Qui usiamo una lambda per sommare tutti gli elementi.
    DIM Somma = AREDUCE(Numeri, FN(acc AS INTEGER, el AS INTEGER) AS INTEGER => acc + el)
    PRINT "Somma di tutti i numeri (AREDUCE): "; Somma
    
    ' Esempio di definizione di una lambda a blocco assegnata a variabile.
    LET FunzioneSommaPari = FUNCTION(acc AS DOUBLE, el AS DOUBLE) AS DOUBLE:
        IF (el MOD 2) = 0 THEN
            acc = acc + el
        END IF
        RETURN acc
    END FUNCTION

    ' Esempio di lambda a blocco definita inline nell'argomento.
    ' Nota: Questa sintassi permette logica complessa dentro l'argomento di una funzione.
    DIM SommaPariInLine = AREDUCE(Numeri, FUNCTION(acc AS DOUBLE, el AS DOUBLE) AS DOUBLE:
        IF (el MOD 2) = 0 THEN
            acc = acc + el
        END IF
        RETURN acc
    END FUNCTION)

    ' Poi, la variabile contenente la lambda viene passata come argomento.
    DIM SommaPari = AREDUCE(Numeri, FunzioneSommaPari)
    PRINT "Somma dei soli numeri pari (AREDUCE con blocco): "; SommaPari

1

u/jcastroarnaud Oct 21 '26

Nice, the language is shaping to be useful.

Answering the question on the original post: a few people would use it if it was open-source, but, considering how few people use Basic (not Visual Basic) and/or Clipper, your language will always be a niche one. So, no pressure for making it a success!

1

u/gmbasic Oct 21 '26

thank you. Yes, I know it will be a niche. My goal is to help people like me who sometimes enjoy programming the old way without AI and want to keep everything simple. This compiler has also a builtin http server with basic server pages, so a basic/clipper programmer could write web apps too.

<%@ IMPORT HTTP, JSON %>
<%@ ROUTE "/" %>
<%
  DIM registry$ = "http://127.0.0.1:8087"
  DIM opts AS HTTPOPTIONS = NEW HTTPOPTIONS
  DIM r = FETCH(registry$ + "/api/packages", opts)
  DIM pkgs = JSON.PARSE(r.Body)
%>
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GMBasic Package Registry</title>
<style>
  :root { color-scheme: light dark; }
  * { box-sizing: border-box; margin: 0; }
  body {
    font-family: -apple-system, "Segoe UI", Roboto, sans-serif;
    background: #f4f6fb; color: #1c2430; line-height: 1.5; padding: 0;
  }
  header {
    background: linear-gradient(135deg, #1e293b, #334155);
    color: #fff; padding: 2rem 2.5rem;
  }
  header h1 { font-size: 1.6rem; letter-spacing: .3px; }
  header p { color: #cbd5e1; margin-top: .3rem; font-size: .95rem; }
  main { max-width: 980px; margin: 2rem auto; padding: 0 1.5rem; }
  .card {
    background: #fff; border: 1px solid #e2e8f0; border-radius: 12px;
    box-shadow: 0 1px 3px rgba(15,23,42,.06); overflow: hidden;
  }
  table { width: 100%; border-collapse: collapse; }
  th {
    text-align: left; font-size: .75rem; text-transform: uppercase;
    letter-spacing: .5px; color: #64748b; background: #f8fafc;
    padding: .7rem 1rem; border-bottom: 1px solid #e2e8f0;
  }
  td { padding: .85rem 1rem; border-bottom: 1px solid #f1f5f9; font-size: .93rem; }
  tr:last-child td { border-bottom: 0; }
  tr:hover td { background: #f8fafc; }
  .name { font-weight: 600; color: #2563eb; text-decoration: none; }
  .name:hover { text-decoration: underline; }
  .ver { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .82rem; color: #334155; }
  .desc { color: #475569; }
  .badge {
    display: inline-block; font-size: .68rem; font-weight: 600;
    padding: .15rem .5rem; border-radius: 999px; background: #e0e7ff; color: #3730a3;
  }
  .count { color: #94a3b8; font-size: .82rem; }
</style>
</head>
<body>
<header>
  <h1>📦 GMBasic Package Registry</h1>
  <p><%= pkgs.Count() %> pacchetti disponibili — installa con <code>PACKAGE INSTALL &lt;nome&gt;</code></p>
</header>
<main>
  <div class="card">
    <table>
      <thead>
        <tr><th>Pacchetto</th><th>Versione</th><th>Descrizione</th></tr>
      </thead>
      <tbody>
        <% FOR EACH k IN JSON.KEYS(pkgs) %>
          <%
            DIM nm = pkgs[k]["name"]
            PRINT "<tr><td><a class='name' href='/package.bsp?name=" + nm + "'>" + nm + "</a></td><td><span class='ver'>" + pkgs[k]["version"] + "</span></td><td class='desc'>" + pkgs[k]["description"] + "</td></tr>"
          %>
        <% NEXT %>
      </tbody>
    </table>
  </div>
  <p class="count" style="margin-top:1rem">Servito da GMBasic BSP (Basic Server Pages)</p>
  <nav style="margin-top:1.5rem;display:flex;gap:.8rem;flex-wrap:wrap">
    <a class="name" href="/register.bsp">Registrati</a>
    <a class="name" href="/publish.bsp">Pubblica</a>
    <a class="name" href="/owners.bsp">Owners</a>
    <a class="name" href="/yank.bsp">Yank</a>
    <a class="name" href="/admin.bsp">Admin</a>
  </nav>
</main>
</body>
</html>

Basic Http Server Example

IMPORT HTTP
SUB HelloHandler(req AS HTTPREQUEST, res AS HTTPRESPONSE)
  res.Send("<h1>Ciao da GM-BASIC!</h1>")
END SUB

SUB DataHandler(req AS HTTPREQUEST, res AS HTTPRESPONSE)
  res.SetCookie("session", "abc123")
  res.Send("ok")
END SUB

DIM cfg = NEW HTTPCONFIG
cfg.Port = 8080
HTTP CONFIG cfg
HTTP ROUTE "GET", "/hello", HelloHandler
HTTP ROUTE "GET", "/data", DataHandler
PRINT "Server sulla porta "; cfg.Port