taiji language 0.1

  This program is used to demonstrate and test compilation, not a part of bootstrap of taijilang.
  It is not tested yet.

require "./require"
fs =  require "fs"
tj =  require "./tj"
repl =  require "./repl"
isValidFlag = /-h\b|-r\b|-v\b|-b\b/
error = (err) ->
   console.error err.message
   process.exit 1

help_str = '''
Usage: taiji [-h] [-r] [-v] [-b] [<infile>] [<outfile>]

Also compile stdin to stdout
eg. $ echo 'console.log \"hello\"' | lispy

<no arguments>    Run REPL
-h                Show this help
-r                Compile and run
-v                Show Version
-b                Create browser-bundle.js in same folder.
<infile>          Input file to compile
<outfile>         Output JS file. If not given
                 <outfile> will be <infile> with .js extension\n'''

// We use maybe monad to carry out each step, so that we can
// halt the operation anytime in between if needed.

extern! doMonad  maybeMonad
doMonad maybeMonad

  // Start maybe Monad bindings
  // First step get args without the first two node and lispy.
  args = process.argv.slice 2

  // get the first arg
  arg1 = args.shift()

  // when no args do stdin -> stdout compile or run repl and return null to
  // halt operations.
extern! noargs \when isUndefined setTimeout
noargs
    \when isUndefined(arg1)
      input = process.stdin
      output = process.stdout
      input.resume()
      input.setEncoding "utf8"
      source = ""
      // Accumulate text form input until it ends.
      input.on "data" (chunck) -> source += chunck.toString()
      // Once input ends try to compile & write to output.
      input.on "end" ->
        /.  try
            output.write tj._compile source process.cwd
            error()
          catch then print 'ok'
      input.on "error" error
      output.on "error" error
      setTimeout ->
          if input.bytesRead = 0 then
            begin!
              input.removeAllListeners "data"
              repl.runrepl 20
      null

   // If arg1 = flag verify valid flag and halt
   // otherwise set arg1 to next arg in args
   extern! flag Error run infile outfile unless
   flag
    \when "-"==arg1./0
      var flag = arg1
      arg1 = args.shift()
      if isValidFlag.test(flag) then
        flag
        error: new: Error "Error: Invalid flag "+flag

    run
    /.switch flag
      "-h": console.log help_str null
      "-v": console.log "Version "+tj.version null
      "-b":
            var bundle
            require.resolve "lispyscript/lib/browser-bundle.js"
            fs.createReadStream(bundle).pipe
            fs.createWriteStream "browser-bundle.js"
            null
      "-r": true
  

  // if infile undefined
  infile
    if arg1 then arg1
    else error: new: Error "Error: No Input file given"

  // set outfile args.shift. ! outfile set outfile to infile.js
  outfile
    begin!
      outfile = args.shift()
      unless outfile
        outfile = infile.replace /\.ls$/ ".js"
        if outfile==infile then
          error: new: Error: "Error: Input file must have extension '.tj'"
      outfile

  // compile infile to outfile. if not run return null.
  extern! js tryDo node
  js
    tryDo
      fs.writeFileSync outfile
        tj._compile 
          fs.readFileSync infile "utf8"
          infile
      "utf8"
      if run then run() else null
      (err) ->
        error err
        null                     // end of maybe Monad bindings

  // we are here if -r true, so run it!
  ->
    require "child_process"
    node.spawn outfile() {stdio: "inherit"}