Advertisement
incinirate

Sammich Compiler

Nov 27th, 2014
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.59 KB | None | 0 0
  1. local tArgs = {...}
  2.  
  3. if #tArgs<1 then
  4.   printError("Usage: sammc <prgm>")
  5.   return
  6. end
  7.  
  8. if not fs.exists(tArgs[1]) or fs.isDir(tArgs[1]) then
  9.   printError("Usage: sammc <prgm>")
  10.   return
  11. end
  12.  
  13. local funcs = {
  14.   ["print"] = {
  15.     1,
  16.     {
  17.       "print(",1,
  18.     },
  19.     ")",
  20.   },
  21.   ["store"] = {
  22.     2,
  23.     {
  24.       "",1,
  25.       " = ",2,
  26.     },
  27.     "",
  28.   },
  29.   ["concat"] = {
  30.     2,
  31.     {
  32.       "",1,
  33.       " = ",1,
  34.       "..",2
  35.     },
  36.     "",
  37.   },
  38.   ["read"] = {
  39.     1,
  40.     {
  41.       "",1,
  42.       " = read()"
  43.     },
  44.     "",
  45.   }
  46. }
  47.  
  48. local inFile = fs.open(tArgs[1],"r")
  49.  
  50. function trim(s)
  51. --  print(s)
  52.  
  53.   return s:match "^%s*(.-)%s*$",s:find("[^ ]")
  54. end
  55.  
  56. local lineCount = 0
  57. function parse(line)
  58.   line = trim(line)
  59.   for k,v in pairs(funcs) do
  60.     if k==line then
  61.       local fArgs = {}
  62.       for i=1,v[1] do
  63.         nxtLine = inFile.readLine()
  64.         if not nxtLine then
  65.           printError("Unexpected EOF:"..lineCount)
  66.           error()
  67.         end
  68.         lineCount = lineCount+1
  69.         local ln = trim(nxtLine)
  70.         table.insert(fArgs,ln)
  71.       end
  72.       local endLine = ""
  73.       local kk = 1
  74.       repeat
  75.         endLine = endLine..(v[2][kk] or "")
  76.         endLine = endLine..(fArgs[v[2][kk+1]] or "")
  77.         kk = kk+2
  78.       until kk>#v[2]
  79.       endLine = endLine..v[3]
  80.       return endLine
  81.     end
  82.   end
  83. end
  84.  
  85. local outStream = fs.open(tArgs[1]..".lua","w")
  86.  
  87. while true do
  88.   line = inFile.readLine()
  89.   lineCount = lineCount+1
  90.   if not line then break end
  91.   token = parse(line)
  92.   print(token)
  93.   outStream.write(token.."\n")
  94. end
  95.  
  96. outStream.close()
  97. inFile.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement