david50407
11/12/2015 - 7:54 PM

Platform indepedent standard library for Crystal

Platform indepedent standard library for Crystal

module OS
  module Windows
    lib LibC
      fun printf(format : UInt32*, args : UInt32) : NoReturn
      # and other LibC bindings
    end

    module CWrapper
      extend self

      macro def printf(format, args) : Nil
        LibC.printf(format.to_uint32, args)
        nil
      end
    end
  end
end
require "./c_wrapper"

module Kernel
  def printf(format, args)
    # Call platform indepedent method
    CWrapper.printf(format, args)
  end
end

# Call platform-specific method
ifdef linux
  OS::Linux::CWrapper.linux_only_method _args
end
module OS
  module Linux
    lib LibC
      fun printf(format : UInt8*, args : UInt32) : NoReturn
      # and other LibC bindings
    end

    module CWrapper
      extend self

      macro def printf(format, args) : Nil
        LibC.printf(format, args)
        nil
      end
      
      macro def linux_only_method(args) : Int32
        # some lib call
      end
    end
  end
end
lib LibC
  # Common bindings go here
  fun chdir(...)
  fun printf(...)
  fun wprintf(...)
  fun atoi(...)
  fun watoic(...)
end

ifdef windows
  require "./windows_c_wrapper"
elsdef linux
  require "./linux_c_wrapper"
end
ifdef linux
  require "./linux_c_wrapper"
elsif windows
  require "./windows_c_wrapper"
end

module CWrapper
  ifdef linux
    IMPL = OS::Linux::CWrapper
  elsif windows
    IMPL = OS::Linux::CWrapper
  end
  
  extend self
  
  # This is just an example.
  macro def printf(format, args) : Nil
    {{IMPL}}.printf(format, args)
  end
end