How to print with --prelude empty?

Hello.

crystal run --prelude empty script.cr

How can I output a string when using --prelude empty ?


Here is one way. Any other ideas?

lib LibC
  fun puts(s : Pointer(UInt8)) : Int32  
  fun exit(status : Int32) : NoReturn
end

fun __crystal_raise_overflow : NoReturn
  LibC.exit(1)
end

ptr = Pointer(UInt8).malloc(5)  
(ptr + 0).value = 'H'.ord.to_u8  
(ptr + 1).value = 'e'.ord.to_u8  
(ptr + 2).value = 'l'.ord.to_u8  
(ptr + 3).value = 'l'.ord.to_u8  
(ptr + 4).value = 'o'.ord.to_u8  
  
LibC.puts(ptr)

I usually use printf, remember to append a \n to the format so it will flush on your terminal.

The compiler knows about String. String literals are instances of that class. You might need to declare it as in the std-lib, just the ivars and the to_unsafe should be enough.

To avoid GC you will need the gc_none flag and require just that.

There are some threads/issues about splitting std-lib in a core part and being able to require just that.

Another alternative might be GitHub - ysbaddaden/nanolib.cr: Minimal alternative corelib for the Crystal programming language

1 Like

You must implement String#to_unsafe to be able to pass string literals:

class String
  def to_unsafe
    pointerof(@c)
  end
end

Then There’s a bunch of other functions that are needed, and nanolib do 'em all (and more).

1 Like

A minimal example for printing a string with empty prelude:

lib LibC
  fun puts(s : Pointer(UInt8)) : Int32
end

class String
  def to_unsafe
    pointerof(@c)
  end
end

LibC.puts("Hello, empty prelude!")
1 Like