From 73a4e6134c0ae131b68dd946bd9f585dd21b97ee Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Mon, 23 Mar 2015 12:30:32 +0100 Subject: Add output formatter --- format.go | 34 ++++++++++++++++++++++++++++++++++ lexer.go | 13 +++++++------ parser.y | 8 ++++---- 3 files changed, 45 insertions(+), 10 deletions(-) create mode 100644 format.go diff --git a/format.go b/format.go new file mode 100644 index 0000000..5a554eb --- /dev/null +++ b/format.go @@ -0,0 +1,34 @@ +package main + +import "fmt" + +type S string +type I int64 +type F float64 +type C complex128 + +func (s S) String() string { + return string(s) +} + +func (i I) String() string { + pre := "" + if i < 0 { + pre = "¯" + i = -i + } + return fmt.Sprint(pre, int64(i)) +} + +func (f F) String() string { + pre := "" + if f < 0 { + pre = "¯" + f = -f + } + return fmt.Sprint(pre, int64(f)) +} + +func (c C) String() string { + return fmt.Sprint(F(real(c)), "J", F(imag(c))) +} diff --git a/lexer.go b/lexer.go index e5e025b..a52cc96 100644 --- a/lexer.go +++ b/lexer.go @@ -28,23 +28,24 @@ func (y *yyLex) Lex(lval *yySymType) int { item := <-y.items switch item.typ { case STRING: - lval.sval = item.val + lval.sval = S(item.val) case QUOTED: - lval.sval = strings.Replace(item.val, "''", "'", -1) + lval.sval = S(strings.Replace(item.val, "''", "'", -1)) case INTEGER: item.val = strings.Replace(item.val, "¯", "-", -1) - lval.ival, _ = strconv.ParseInt(item.val, 10, 64) + v, _ := strconv.ParseInt(item.val, 10, 64) + lval.ival = I(v) case FLOAT: item.val = strings.Replace(item.val, "¯", "-", -1) - lval.fval, _ = strconv.ParseFloat(item.val, 64) + v, _ := strconv.ParseFloat(item.val, 64) + lval.fval = F(v) case COMPLEX: item.val = strings.Replace(item.val, "¯", "-", -1) pos := strings.IndexAny(item.val, "jJ") r, _ := strconv.ParseFloat(item.val[:pos], 64) i, _ := strconv.ParseFloat(item.val[pos+1:], 64) - lval.cval = complex(r, i) + lval.cval = C(complex(r, i)) } - lval.sval = item.val return item.typ } diff --git a/parser.y b/parser.y index 3d438e9..735d22f 100644 --- a/parser.y +++ b/parser.y @@ -5,10 +5,10 @@ import "fmt" %} %union { - sval string - ival int64 - fval float64 - cval complex128 + sval S + ival I + fval F + cval C } %token STRING QUOTED -- cgit v1.2.3