Skip to content

Commit

Permalink
Add irb with minimal support
Browse files Browse the repository at this point in the history
  • Loading branch information
elct9620 committed Sep 25, 2024
1 parent 782fce1 commit c4577b8
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
51 changes: 51 additions & 0 deletions cmd/irb/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package main

import (
"bufio"
"fmt"
"os"

"github.com/elct9620/mruby-go"
)

const (
exitCommand = "exit"
inputPrompt = "> "
outputPrompt = "=>"
)

func main() {
mrb, err := mruby.New()
if err != nil {
panic(err)
}

fmt.Print("mirb - Embeded Interactive Ruby Shell (Go Edition)\n\n")
fmt.Print(inputPrompt)

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if line == exitCommand {
break
}

ret, err := mrb.LoadString(line)

// NOTE: ret may be error
errRet, ok := ret.(error)
if ok {
err = errRet
}

if err != nil {
fmt.Println(err)
} else {
if ret != nil {
fmt.Printf(" %s %s\n", outputPrompt, mrb.Inspect(ret))
}
}

fmt.Print(inputPrompt)
}
}
13 changes: 13 additions & 0 deletions kernel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ package mruby

import "fmt"

func (mrb *State) Inspect(obj Value) string {
ret, ok := objectInspect(mrb, obj).(string)
if !ok {
return ""
}

return ret
}

func objectInspect(mrb *State, self Value) Value {
switch v := self.(type) {
case *Object:
Expand All @@ -10,6 +19,10 @@ func objectInspect(mrb *State, self Value) Value {
case RClass:
name := mrb.ObjectInstanceVariableGet(v, _classname(mrb))
return name
case string:
return fmt.Sprintf("%q", v)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return fmt.Sprintf("%d", v)
default:
return nil
}
Expand Down

0 comments on commit c4577b8

Please sign in to comment.