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