%
% This program endeavors to exercise the backend a lot,
% though not necessarily the optimizer.
%
% quash various parts of the output
% in order to get "just the instructions"
% and also avoid host file system paths (in the debug information)
%
% If we were more concerned, we could have coverage
% over various sets of options, optimized and not,
% position independent and not, debug info more or less or none, etc.
%
% split into multiple modules to keep size down
% when it gets too large, compiler backend fails
%

m3back_debug = ""
m3back_optimize = ""
m3back_pic = ""
m3back_unwind_table = "-fno-asynchronous-unwind-tables"
M3_BOOTSTRAP = TRUE
M3_KEEP_FILES = TRUE

include("Math.quake")

proc BeginInterface(a) is
  if equal(M3_MODE, "clean")
    return "/dev/null"
  end
  local b = a & ".i3.temp"
  > b in
    write("INTERFACE ", a, ";", CR)
  end
  return b
end

proc EndX(a, ext) is
  if equal(M3_MODE, "clean")
    return
  end
  local b = a & ext & ".temp"
  >> b in
    write("END ", a, ".", CR)
  end
  cp_if(b, a & ext)
end

proc EndInterface(a) is
  EndX(a, ".i3")
end

proc EndModule(a) is
  if equal(M3_MODE, "clean")
    return
  end
  >> a & ".m3.temp" in
    write("BEGIN", CR)
  end
  EndX(a, ".m3")
end

proc ToLong(name, fromType, toLong) is
  if not toLong or IsLong{fromType}
    return name
  end
  return "VAL(" & name & ", LONGINT)"
end

local params = [FALSE, TRUE] % or (global) variable (future: nested)
local L = {8:"",16:"",32:"",64:"L"}
local IsLong = {8:FALSE,16:FALSE,32:FALSE,64:TRUE}

local IsInt = { }
local IsFloat = { }
local IsUnsignedInt = { }
local IsSignedInt = { }
local IntSize = { }
local Types = { }
local IntTypes = { }
local ShortName = { }
local Builtin = { }
foreach size in [8,16,32,64]
  foreach unsigned in [TRUE, FALSE]
    local t = {FALSE:"",TRUE:"U"}{unsigned} & "INT" & size
    Types{t} = 1
    Builtin{t} = FALSE
    IntSize{t} = size
    IsInt{t} = TRUE
    IsFloat{t} = FALSE
    IsUnsignedInt{t} = unsigned
    IsSignedInt{t} = not unsigned
    IsLong{t} = IsLong{size}
    L{t} = L{size}
    IntTypes{t} = 1
    ShortName{t} = {FALSE:"i",TRUE:"u"}{unsigned} & size
  end
end

foreach t in ["INTEGER", "CARDINAL", "LONGINT", "LONGCARD"]
  Types{t} = 1
  IntTypes{t} = 1
  IsInt{t} = TRUE
  IsFloat{t} = FALSE
  ShortName{t} = t
  Builtin{t} = TRUE
end

ShortName{"INTEGER"} = "I"
ShortName{"LONGINT"} = "L"
ShortName{"CARDINAL"} = "C"
ShortName{"LONGCARD"} = "LC"

foreach t in ["INTEGER", "CARDINAL"]
  IntSize{t} = {"32BITS":32,"64BITS":64}{WORD_SIZE}
end

foreach t in ["INTEGER", "CARDINAL"]
  L{t} = ""
end

foreach t in ["INTEGER", "CARDINAL", "FLOAT32"]
  IsLong{t} = FALSE
end

foreach t in ["LONGINT", "LONGCARD"]
  IntSize{t} = 64
  L{t} = "L"
end

foreach t in ["LONGINT", "LONGCARD", "FLOAT64"]
  IsLong{t} = TRUE
end

L{"FLOAT32"} = "e0"
L{"FLOAT64"} = "d0"

foreach t in ["INTEGER", "LONGINT"]
  IsUnsignedInt{t} = FALSE
  IsSignedInt{t} = TRUE
end

foreach t in ["CARDINAL", "LONGCARD"]
  IsUnsignedInt{t} = TRUE
  IsSignedInt{t} = FALSE
end

local FloatTypes = {"FLOAT32", "FLOAT64"} % "FLOATX"
foreach t in FloatTypes
  Types{t} = 1
  IsInt{t} = FALSE
  IsFloat{t} = TRUE
  Builtin{t} = TRUE % special
  IsUnsignedInt{t} = FALSE
  IsSignedInt{t} = FALSE
  IntSize{t} = 0
  ShortName{t} = {"FLOAT32":"f32", "FLOAT64":"f64"}{t}
  IsLong{t} = FALSE % needs work
end

IntSize{"Word"} = IntSize{"INTEGER"}
IntSize{"Long"} = IntSize{"LONGINT"}

local proc comment(a) is
  if equal(M3_MODE, "clean")
    return
  end
  write(CR, "(* ", a, " *)", CR, CR)
end

proc BeginModule(a) is
  if equal(M3_MODE, "clean")
    return "/dev/null"
  end
  >> BeginInterface(a) in
  end
  EndInterface(a)
  derived_interface(a, HIDDEN)
  derived_implementation(a)

  local b = a & ".m3.temp"
  > b in
    write("MODULE ", a, ";", CR)
    write("<*NOWARN*>IMPORT Cstdint, Word, Long;", CR)

    comment("define some types")

    write("<*NOWARN*>TYPE FLOAT32 = REAL;",CR)
    write("<*NOWARN*>TYPE FLOAT64 = LONGREAL;",CR)

    foreach t in Types
      if IsInt{t} and not Builtin{t}
        write("<*NOWARN*>TYPE ", t, " = Cstdint.", {FALSE:"",TRUE:"u"}{IsUnsignedInt{t}}, "int", IntSize{t}, "_t;", CR)
      end
    end

    comment("constants")

    foreach t in Types
      write("<*NOWARN*> CONST k", ShortName{t}, ":", t, "=", Increment())
      if IsFloat{t}
        write(".", Increment())
      else
      end
      write(L{t}, ";", CR)
    end

    comment("variables")

    foreach t in Types
      write("<*NOWARN*> VAR v", ShortName{t}, ":", t, ":=", Increment())
      if IsFloat{t}
        write(".", Increment())
      else
      end
      write(L{t}, ";", CR)
    end
    write("<*NOWARN*>VAR offset, count:CARDINAL;", CR)
  end
  return b
end

>> BeginModule("return_constant") in
  comment("functions that return constants")

  foreach t in Types
    local f = "ret_k" & ShortName{t}
    write("<*NOWARN*>PROCEDURE ", f, "():", t, "=BEGIN RETURN k", ShortName{t}, ";END ", f, ";", CR)
  end
end
EndModule("return_constant")

>> BeginModule("return_variable") in
  comment("functions that return variables")

  foreach t in Types
    local f = "ret_v" & ShortName{t}
    write("<*NOWARN*>PROCEDURE ", f, "():", t, "=BEGIN RETURN v", ShortName{t}, ";END ", f, ";", CR)
  end
end
EndModule("return_variable")

>> BeginModule("return_parameter") in
  comment("functions that return parameters")

  foreach t in Types
    local f = "ret_p" & ShortName{t}
    write("<*NOWARN*>PROCEDURE ", f, "(p:", t, "):", t, "=BEGIN RETURN p", ";END ", f, ";", CR)
  end
end
EndModule("return_parameter")

>> BeginModule("return_parameter_convert") in
  comment("functions that return parameters converted to another type")
  % (needs work, e.g. for float)

  foreach t in IntTypes
    foreach t2 in IntTypes
      local f = "ret_" & ShortName{t} & "_" & ShortName{t2}
      local toLong = (not IsLong{t}) and IsLong{t2}
      local isLong = IsLong{t} or IsLong{t2}
      write("<*NOWARN*>PROCEDURE ", f, "(a:", t, "):",)
      if isLong
        write("LONGINT")
      else
        write("INTEGER")
      end
      write("=BEGIN RETURN ", ToLong("a", t, toLong), ";END ", f, ";", CR)
    end
  end
end
EndModule("return_parameter_convert")

% compat with existing files
local filenames = {"Insert":"insert", "Extract":"extract"}
local all_ops = ["Plus", "Times", "Minus", "Divide", "Mod", "LT", "LE", "GT",
                 "GE", "And", "Or", "Xor", "EQ", "NE", "Not",
                 "LeftShift", "RightShift", "Shift",
                 "LeftRotate", "RightRotate", "Rotate",
                 "Insert", "Extract"]
local binary_ops = {"Plus", "Times", "Minus", "Divide", "Mod", "LT", "LE", "GT",
                    "GE", "And", "Or", "Xor", "EQ", "NE",
                    "LeftShift", "RightShift", "Shift",
                    "LeftRotate", "RightRotate", "Rotate",
                    "Insert"}
local shift_ops = {"LeftShift", "RightShift", "Shift",
                   "LeftRotate", "RightRotate", "Rotate"}
local bitfield_ops = {"Insert", "Extract"}
local unary_ops = {"Not"}
local word_ops = {"Plus", "Times", "Minus", "Divide",
                  "Mod", "LT", "LE", "GT", "GE",
                  "And", "Or", "Xor", "Not",
                  "LeftShift", "RightShift", "Shift",
                  "LeftRotate", "RightRotate", "Rotate",
                  "Insert", "Extract"}
local float_ops = {"Plus":"+", "Minus":"-", "Times":"*", "Divide":"/",
                   "Mod":"MOD", "LT":"<", "LE":"<=", "GT":">", "GE":">=",
                   "EQ":"=", "NE":"#", "Not":"-"}
local int_ops = {"Plus":"+", "Minus":"-", "Times":"*", "Divide":"DIV",
                 "Mod":"MOD", "LT":"<", "LE":"<=", "GT":">", "GE":">=",
                 "EQ":"=", "NE":"#", "Not":"-"}
local ret_bool = {"LT", "LE", "GT", "GE", "EQ", "NE"}

foreach op in all_ops
  local filename = op
  if filenames contains op
    filename = filenames{op}
  end
  >> BeginModule(filename) in
    comment(op)
    foreach t in Types
      foreach t2 in Types
        foreach p in params
          foreach word in [TRUE, FALSE]
            foreach float in [TRUE, FALSE]
              % "continue" would be nice
              if ((word and (not float) and word_ops contains op and IsInt{t} and IsInt{t2})
                  or ((not word) and float and float_ops contains op and (not IsInt{t}) and (not IsInt{t2}))
                  or ((not word) and (not float) and int_ops contains op and IsInt{t} and IsInt{t2}))
                  and ((IsInt{t} and IsInt{t2}) or (equal(t, t2) and float_ops contains op))
                  and (binary_ops contains op or equal(t, t2))
                  and ((IsInt{t} and (equal(t2, "INTEGER") or equal(t2, "CARDINAL"))) or not shift_ops contains op)
                  and ((IsInt{t} and equal(t, t2)) or not bitfield_ops contains op)
                local f = op & "_" & {TRUE:"param",FALSE:"var"}{p} & "_" & ShortName{t} & "_" & ShortName{t2}
                if word
                  f = "u" & f
                end                  
                write("<*NOWARN*>PROCEDURE ", f, "(")
                if p
                  write("a:", t, ";b:", t2)
                  if bitfield_ops contains op
                    write(";offset,count:CARDINAL")
                  end
                end
                write("):")
                local toLong = not equal(IsLong{t}, IsLong{t2}) and not shift_ops contains op
                local isLong = IsLong{t} or IsLong{t2}
                if ret_bool contains op
                  write("BOOLEAN")
                else
                  if word
                    if isLong
                      write("Long.T")
                    else
                      write("Word.T")
                    end
                  else
                    if isLong
                      write("LONGINT")
                    else
                      write(t)
                    end
                  end
                end
                write("=BEGIN RETURN ")
                local a = "a"
                local b = "b"
                if not p
                  a = "v" & ShortName{t}
                  b = "v" & ShortName{t2}
                end
                a = ToLong(a, t, toLong)
                b = ToLong(b, t2, toLong)
                if word
                  local Word = {FALSE:"Word","TRUE":"Long"}{isLong}
                  write(Word, ".", op, "(", a)
                  if binary_ops contains op
                    write(",", b)
                  end
                  if bitfield_ops contains op
                    write(",offset,count")
                  end
                  write(")")
                else
                  if binary_ops contains op
                    write(a, " ")
                  end
                  write({TRUE:float_ops,FALSE:int_ops}{float}{op}, " ", b)
                end
                write(";END ", f, ";", CR)
              end
            end
          end
        end
      end
    end
  end
  EndModule(filename)
end

>> BeginModule("bitfield") in
  comment("bit field get and set")
  n = IntSize{"INTEGER"} & ""
  foreach i in InclusiveRange("1", n)
    foreach j in InclusiveRange("1", Sub(n, i))
      local t = "BitField_offset" & i & "_count" & j
      write("<*NOWARN*>TYPE ", t, " = RECORD ", CR)
      local proc WriteBitField(name, bits) is
        write(" ", name, ":BITS ", bits, " FOR ")
        write(" [0 .. Word.RightShift(Word.Not(0), ", Sub(n, bits), ")]")
        write(";", CR)
      end
      WriteBitField("offset", i)
      WriteBitField("value", j)
      write("END;", CR)
      local p = "read_var_" & t
      write("<*NOWARN*> PROCEDURE ", p, "(a:", t, "):INTEGER=", CR,
            "             BEGIN RETURN a.value END ", p, ";", CR)
      p = "write_var_" & t
      write("<*NOWARN*> PROCEDURE ", p, "(VAR a:", t, ";b:INTEGER)=", CR,
           "              BEGIN a.value := b END ", p, ";", CR)
    end
  end
end
EndModule("bitfield")

>> BeginModule("div_pow2") in
  comment("divide by powers of 2")
  foreach t in ["INT32", "UINT32", "INT64", "UINT64", "INTEGER", "CARDINAL", "LONGINT", "LONGCARD"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      local p = "div_pow2_" & ShortName{t} & "_" & i
      write("<*NOWARN*> PROCEDURE ", p, "(a:", t, "):", t, "=", CR,
            "           BEGIN RETURN a DIV 16_" & HexPowerOf2(i) & L{t} & " END ", p, ";", CR)
    end
  end
end
EndModule("div_pow2")

>> BeginModule("mod_pow2") in
  comment("mod by powers of 2")
  foreach t in ["INT32", "UINT32", "INT64", "UINT64", "INTEGER", "CARDINAL", "LONGINT", "LONGCARD"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      local p = "mod_pow2_" & ShortName{t} & "_" & i
      write("<*NOWARN*> PROCEDURE ", p, "(a:", t, "):", t, "=", CR,
            "           BEGIN RETURN a MOD 16_" & HexPowerOf2(i) & L{t} & " END ", p, ";", CR)
    end
  end
end
EndModule("mod_pow2")

>> BeginModule("insert_constant_offset") in
  comment("insert with constant offset")
  foreach t in ["Word", "Long"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      local p = t & "_insert_constant_offset_" & i
      write("<*NOWARN*> PROCEDURE ", p, "(a,b:", t, ".T):", t, ".T=", CR,
            "           BEGIN RETURN ", t, ".Insert(a,b,", i, ",count); END ", p, ";", CR)
    end
  end
end
EndModule("insert_constant_offset")

>> BeginModule("insert_constant_count") in
  comment("insert with constant count")
  foreach t in ["Word", "Long"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      local p = t & "_insert_constant_count_" & i
      write("<*NOWARN*> PROCEDURE ", p, "(a,b:", t, ".T):", t, ".T=", CR,
            "           BEGIN RETURN ", t, ".Insert(a,b,offset,", i, "); END ", p, ";", CR)
    end
  end
end
EndModule("insert_constant_count")

>> BeginModule("insert_constant_both") in
  comment("insert with constant offset and count")
  foreach t in ["Word", "Long"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      foreach j in InclusiveRange("0", Sub(IntSize{t}, i))
        local p = t & "_insert_constants_" & i & "_" & j
        write("<*NOWARN*> PROCEDURE ", p, "(a,b:", t, ".T):", t, ".T=", CR,
              "           BEGIN RETURN ", t, ".Insert(a,b,",i,",",j,"); END ", p, ";", CR)
      end
    end
  end
end
EndModule("insert_constant_both")

>> BeginModule("extract_constant_offset") in
  comment("extract with constant offset")
  foreach t in ["Word", "Long"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      local p = t & "_extract_constant_offset_" & i
      write("<*NOWARN*> PROCEDURE ", p, "(a:", t, ".T):", t, ".T=", CR,
            "           BEGIN RETURN ", t, ".Extract(a,", i, ",count); END ", p, ";", CR)
    end
  end
end
EndModule("extract_constant_offset")

>> BeginModule("extract_constant_count") in
  comment("extract with constant count")
  foreach t in ["Word", "Long"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      local p = t & "_extract_constant_count_" & i
      write("<*NOWARN*> PROCEDURE ", p, "(a:", t, ".T):", t, ".T=", CR,
            "           BEGIN RETURN ", t, ".Extract(a,offset,", i, "); END ", p, ";", CR)
    end
  end
end
EndModule("extract_constant_count")

>> BeginModule("extract_constant_both") in
  comment("extract with constant offset and count")
  foreach t in ["Word", "Long"]
    foreach i in InclusiveRange(0, Sub(IntSize{t}, 1))
      foreach j in InclusiveRange("0", Sub(IntSize{t}, i))
        p = t & "_extract_constants_" & i & "_" & j
        write("<*NOWARN*> PROCEDURE ", p, "(a:", t, ".T):", t, ".T=", CR,
             "            BEGIN RETURN ", t, ".Extract(a,",i,",",j,"); END ", p, ";", CR)
      end
    end
  end
end
EndModule("extract_constant_both")

>> BeginModule("records") in
  comment("records")
  foreach t in ["CHAR", "BOOLEAN", "WIDECHAR", "INT32", "UINT32", "INT64", "UINT64", "INTEGER", "CARDINAL", "LONGINT", "LONGCARD", "FLOAT32", "FLOAT64"]
    local hi = 10
    if equal(t, "CHAR")
      hi = 100
    end
    foreach i in InclusiveRange(1, hi)
      local p = "R" & t & i
      write("TYPE ", p, " = RECORD a:ARRAY[0..", Sub(i, 1), "] OF ", t, "; END;", CR)
      write("<*NOWARN*> PROCEDURE A", p, "(a:", p, "):", t, "=BEGIN RETURN a.a[", Div(i, 2), "]; END A", p, ";", CR)
      write("<*NOWARN*> PROCEDURE B", p, "(a:", p, "):", p, "=BEGIN RETURN a; END B", p, ";", CR)
      write("<*NOWARN*> PROCEDURE C", p, "(b:INTEGER;a:", p, "):", t, "=BEGIN RETURN a.a[", Div(i, 2), "]; END C", p, ";", CR)
      write("<*NOWARN*> PROCEDURE D", p, "(b:INTEGER;a:", p, "):", p, "=BEGIN RETURN a; END D", p, ";", CR)
      write("<*NOWARN*> PROCEDURE E", p, "(a:", p, ";b:INTEGER):", t, "=BEGIN RETURN a.a[", Div(i, 2), "]; END E", p, ";", CR)
      write("<*NOWARN*> PROCEDURE F", p, "(a:", p, ";b:INTEGER):", p, "=BEGIN RETURN a; END F", p, ";", CR)
    end
  end
end
EndModule("records")

module("RegExpParse")
module("RegExpTok")
module("Div")
implementation("Main")
build_standalone()
include ("../../Test.common")
