How can I use Crystal compiler as a library?

Finally, I’ve managed to use the compiler as a library!

crystal init app duck_egg
cd duck_egg
vi shard.yml
name: duck_egg
version: 0.1.0

authors:
  - kojix2 <2xijok@gmail.com>

targets:
  🥚:
    main: src/duck_egg.cr

dependencies:
  markd:
    github: icyleaf/markd
  reply:
    github: I3oris/reply

crystal: '>= 1.15.1'

license: MIT
vi src/duck_egg.cr
require "compiler/requires"

BIRDS = [
  { "🐔", "cluck!" },
  { "🐓", "cock-a-doodle-doo" },
  { "🦃", "gobble" },
  { "🦆", "quack" },
  { "🦉", "hoot" },
  { "🦜", "squawk" },
  { "🕊", "coo" },
  { "🦢", "honk" },
  { "🦩", "brrrrt" },
  { "🐧", "honk honk" },
  { "🦤", "boop" },
  { "🦕", "Bwooooon!!" },
  { "🦖", "Raaaaawr!!" }
]

bird, sound = BIRDS.sample

compiler = Crystal::Compiler.new
source = Crystal::Compiler::Source.new(bird, %Q(puts "#{bird}  < #{sound}"))
compiler.compile source, bird
shards build
# Check CRYSTAL_PATH
crystal env
# Set env
export CRYSTAL_PATH=lib:/usr/local/bin/../share/crystal/src
bin/🥚
./🦖

:t_rex: < Raaaaawr!!

6 Likes