From 3863427127d4c87e00328b78ceba7386c438637f Mon Sep 17 00:00:00 2001 From: Nigel Tao Date: Fri, 9 Jun 2017 12:26:00 +1000 Subject: [PATCH] Add user-defined error and status codes. --- cmd/puffs-gen-c/main.go | 136 +++++++++++++++++++++++++++++++++------ gen/c/gif.c | 19 ++++-- gen/h/gif.h | 1 + lang/ast/ast.go | 43 +++++++++++-- lang/check/check.go | 55 +++++++++++++--- lang/check/type.go | 10 ++- lang/parse/parse.go | 34 +++++++++- lang/token/list.go | 6 ++ std/gif/decode_lzw.puffs | 6 ++ test/c/gif/basic.c | 14 ++++ 10 files changed, 282 insertions(+), 42 deletions(-) diff --git a/cmd/puffs-gen-c/main.go b/cmd/puffs-gen-c/main.go index c8bb6146..3ecf96f2 100644 --- a/cmd/puffs-gen-c/main.go +++ b/cmd/puffs-gen-c/main.go @@ -55,15 +55,19 @@ func main() { }) } +const userDefinedStatusBase = 128 + var builtInStatuses = [...]string{ - // For API/ABI compatibility, the very first two statuses must be "status - // ok" (with generated value 0) and "error bad version" (with generated - // value -2 + 1). This lets caller code check the constructor return value - // for "error bad version" even if the caller and callee were built with - // different versions. + // For API/ABI forwards and backwards compatibility, the very first two + // statuses must be "status ok" (with generated value 0) and "error bad + // version" (with generated value -2 + 1). This lets caller code check the + // constructor return value for "error bad version" even if the caller and + // callee were built with different versions. "status ok", "error bad version", - // The order of the remaining statuses is less important. + // The order of the remaining statuses is less important, but should remain + // stable for API/ABI backwards compatibility, where additional built in + // status codes don't affect existing ones. "error bad receiver", "error bad argument", "error constructor not called", @@ -72,6 +76,12 @@ var builtInStatuses = [...]string{ "status short write", } +func init() { + if len(builtInStatuses) > userDefinedStatusBase { + panic("too many builtInStatuses") + } +} + type replacementPolicy bool const ( @@ -101,6 +111,12 @@ const ( const maxTemp = 10000 +type status struct { + name string + msg string + isError bool +} + type perFunc struct { jumpTargets map[*a.While]uint32 tempW uint32 @@ -110,11 +126,13 @@ type perFunc struct { } type gen struct { - buffer bytes.Buffer - pkgName string - tm *t.Map - files []*a.File - perFunc perFunc + buffer bytes.Buffer + pkgName string + tm *t.Map + files []*a.File + statusList []status + statusMap map[t.ID]status + perFunc perFunc } func (g *gen) printf(format string, args ...interface{}) { fmt.Fprintf(&g.buffer, format, args...) } @@ -137,6 +155,11 @@ func (g *gen) jumpTarget(n *a.While) (uint32, error) { } func (g *gen) generate() error { + g.statusMap = map[t.ID]status{} + if err := g.forEachStatus(bothPubPri, (*gen).gatherStatuses); err != nil { + return err + } + includeGuard := "PUFFS_" + strings.ToUpper(g.pkgName) + "_H" g.printf("#ifndef %s\n#define %s\n\n", includeGuard, includeGuard) @@ -154,9 +177,14 @@ func (g *gen) generate() error { if strings.HasPrefix(s, "error ") { nudge = "+1" } - s = strings.Replace(s, " ", "_", -1) - s = strings.ToLower(s) - g.printf("puffs_%s_%s = %d%s,\n", g.pkgName, s, -2*i, nudge) + g.printf("%s = %d%s,\n", g.cName(s), -2*i, nudge) + } + for i, s := range g.statusList { + nudge := "" + if s.isError { + nudge = "+1" + } + g.printf("%s = %d%s,\n", s.name, -2*(userDefinedStatusBase+i), nudge) } g.printf("} puffs_%s_status;\n\n", g.pkgName) g.printf("bool puffs_%s_status_is_error(puffs_%s_status s);\n\n", g.pkgName, g.pkgName) @@ -187,7 +215,7 @@ func (g *gen) generate() error { g.writes("// ---------------- Status Codes Implementations\n\n") g.printf("bool puffs_%s_status_is_error(puffs_%s_status s) {"+ "return s & 1; }\n\n", g.pkgName, g.pkgName) - g.printf("const char* puffs_%s_status_strings[%d] = {\n", g.pkgName, len(builtInStatuses)) + g.printf("const char* puffs_%s_status_strings[%d] = {\n", g.pkgName, len(builtInStatuses)+len(g.statusList)) for _, s := range builtInStatuses { if strings.HasPrefix(s, "status ") { s = s[len("status "):] @@ -197,12 +225,19 @@ func (g *gen) generate() error { s = g.pkgName + ": " + s g.printf("%q,", s) } + for _, s := range g.statusList { + g.printf("%q,", g.pkgName+": "+s.msg) + } g.writes("};\n\n") + g.printf("const char* puffs_%s_status_string(puffs_%s_status s) {\n", g.pkgName, g.pkgName) - g.writes("s = -(s >> 1);") - g.printf("if ((0 <= s) && (s < %d)) { return puffs_%s_status_strings[s]; }\n", + g.writes("s = -(s >> 1); if (0 <= s) {\n") + g.printf("if (s < %d) { return puffs_%s_status_strings[s]; }\n", len(builtInStatuses), g.pkgName) - g.writes("return \"\";\n") + g.printf("s -= %d;\n", userDefinedStatusBase-len(builtInStatuses)) + g.printf("if ((%d <= s) && (s < %d)) { return puffs_%s_status_strings[s]; }\n", + len(builtInStatuses), len(builtInStatuses)+len(g.statusList), g.pkgName) + g.printf("}\nreturn \"%s: unknown status\";\n", g.pkgName) g.writes("}\n\n") g.writes("// ---------------- Private Structs\n\n") @@ -261,6 +296,22 @@ func (g *gen) forEachFunc(v visibility, f func(*gen, *a.Func) error) error { return nil } +func (g *gen) forEachStatus(v visibility, f func(*gen, *a.Status) error) error { + for _, file := range g.files { + for _, n := range file.TopLevelDecls() { + if n.Kind() != a.KStatus || + (v == pubOnly && n.Raw().Flags()&a.FlagsPublic == 0) || + (v == priOnly && n.Raw().Flags()&a.FlagsPublic != 0) { + continue + } + if err := f(g, n.Status()); err != nil { + return err + } + } + } + return nil +} + func (g *gen) forEachStruct(v visibility, f func(*gen, *a.Struct) error) error { for _, file := range g.files { for _, n := range file.TopLevelDecls() { @@ -277,6 +328,44 @@ func (g *gen) forEachStruct(v visibility, f func(*gen, *a.Struct) error) error { return nil } +func (g *gen) cName(name string) string { + b := []byte(nil) + b = append(b, "puffs_"...) + b = append(b, g.pkgName...) + b = append(b, '_') + for _, r := range name { + if 'A' <= r && r <= 'Z' { + b = append(b, byte(r+'a'-'A')) + } else if ('a' <= r && r <= 'z') || ('0' <= r && r <= '9') || ('_' == r) { + b = append(b, byte(r)) + } else if ' ' == r { + b = append(b, '_') + } + } + return string(b) +} + +func (g *gen) gatherStatuses(n *a.Status) error { + msg := n.Message().String(g.tm) + if len(msg) < 2 || msg[0] != '"' || msg[len(msg)-1] != '"' { + return fmt.Errorf("bad status message %q", msg) + } + msg = msg[1 : len(msg)-1] + prefix := "status " + isError := n.Keyword().Key() == t.KeyError + if isError { + prefix = "error " + } + s := status{ + name: g.cName(prefix + msg), + msg: msg, + isError: isError, + } + g.statusList = append(g.statusList, s) + g.statusMap[n.Message()] = s + return nil +} + func (g *gen) writeStruct(n *a.Struct) error { // For API/ABI compatibility, the very first field in the struct must be // the status code. This lets the constructor callee set "this->status = @@ -652,14 +741,21 @@ func (g *gen) writeStatement(n *a.Node, depth uint32) error { return nil case a.KReturn: + n := n.Return() + ret := "" + if n.Keyword() == 0 { + ret = fmt.Sprintf("puffs_%s_status_ok", g.pkgName) + } else { + ret = g.statusMap[n.Message()].name + } if !g.perFunc.suspendible { // TODO: consider the return values, especially if they involve // suspendible function calls. g.writes("return;\n") } else if g.perFunc.public { - g.printf("status = puffs_%s_status_ok; goto cleanup0;\n", g.pkgName) + g.printf("status = %s; goto cleanup0;\n", ret) } else { - g.printf("return puffs_%s_status_ok;\n", g.pkgName) + g.printf("return %s;\n", ret) } return nil diff --git a/gen/c/gif.c b/gen/c/gif.c index bf16b7d0..a2344bd1 100644 --- a/gen/c/gif.c +++ b/gen/c/gif.c @@ -63,6 +63,7 @@ typedef enum { puffs_gif_error_unexpected_eof = -10 + 1, puffs_gif_status_short_read = -12, puffs_gif_status_short_write = -14, + puffs_gif_error_bad_gif_image = -256 + 1, } puffs_gif_status; bool puffs_gif_status_is_error(puffs_gif_status s); @@ -121,7 +122,7 @@ bool puffs_gif_status_is_error(puffs_gif_status s) { return s & 1; } -const char* puffs_gif_status_strings[8] = { +const char* puffs_gif_status_strings[9] = { "gif: ok", "gif: bad version", "gif: bad receiver", @@ -130,14 +131,21 @@ const char* puffs_gif_status_strings[8] = { "gif: unexpected EOF", "gif: short read", "gif: short write", + "gif: bad GIF image", }; const char* puffs_gif_status_string(puffs_gif_status s) { s = -(s >> 1); - if ((0 <= s) && (s < 8)) { - return puffs_gif_status_strings[s]; + if (0 <= s) { + if (s < 8) { + return puffs_gif_status_strings[s]; + } + s -= 120; + if ((8 <= s) && (s < 9)) { + return puffs_gif_status_strings[s]; + } } - return ""; + return "gif: unknown status"; } // ---------------- Private Structs @@ -241,6 +249,9 @@ label_0_continue:; } else if (v_code == v_end_code) { status = puffs_gif_status_ok; goto cleanup0; + } else { + status = puffs_gif_error_bad_gif_image; + goto cleanup0; } goto label_0_break; } diff --git a/gen/h/gif.h b/gen/h/gif.h index e8e6cae3..5c6564f4 100644 --- a/gen/h/gif.h +++ b/gen/h/gif.h @@ -63,6 +63,7 @@ typedef enum { puffs_gif_error_unexpected_eof = -10 + 1, puffs_gif_status_short_read = -12, puffs_gif_status_short_write = -14, + puffs_gif_error_bad_gif_image = -256 + 1, } puffs_gif_status; bool puffs_gif_status_is_error(puffs_gif_status s); diff --git a/lang/ast/ast.go b/lang/ast/ast.go index a8c5a019..d8826fc2 100644 --- a/lang/ast/ast.go +++ b/lang/ast/ast.go @@ -31,6 +31,7 @@ const ( KIf KJump KReturn + KStatus KStruct KTypeExpr KUse @@ -58,6 +59,7 @@ var kindStrings = [...]string{ KIf: "KIf", KJump: "KJump", KReturn: "KReturn", + KStatus: "KStatus", KStruct: "KStruct", KTypeExpr: "KTypeExpr", KUse: "KUse", @@ -113,6 +115,7 @@ func (n *Node) If() *If { return (*If)(n) } func (n *Node) Jump() *Jump { return (*Jump)(n) } func (n *Node) Raw() *Raw { return (*Raw)(n) } func (n *Node) Return() *Return { return (*Return)(n) } +func (n *Node) Status() *Status { return (*Status)(n) } func (n *Node) Struct() *Struct { return (*Struct)(n) } func (n *Node) TypeExpr() *TypeExpr { return (*TypeExpr)(n) } func (n *Node) Use() *Use { return (*Use)(n) } @@ -394,16 +397,22 @@ func NewIf(condition *Expr, elseIf *If, bodyIfTrue []*Node, bodyIfFalse []*Node) } } -// Return is "return LHS": +// Return is "return LHS", "return error ID1" or "return status ID1": +// - ID0: <0|IDError|IDStatus> +// - ID1: message // - LHS: type Return Node -func (n *Return) Node() *Node { return (*Node)(n) } -func (n *Return) Value() *Expr { return n.lhs.Expr() } +func (n *Return) Node() *Node { return (*Node)(n) } +func (n *Return) Keyword() t.ID { return n.id0 } +func (n *Return) Message() t.ID { return n.id1 } +func (n *Return) Value() *Expr { return n.lhs.Expr() } -func NewReturn(value *Expr) *Return { +func NewReturn(keyword t.ID, message t.ID, value *Expr) *Return { return &Return{ kind: KReturn, + id0: keyword, + id1: message, lhs: value.Node(), } } @@ -536,6 +545,30 @@ func NewFunc(flags Flags, filename string, line uint32, receiver t.ID, name t.ID } } +// Status is "error ID1" or "status ID1": +// - FlagsPublic is "pub" vs "pri" +// - ID0: +// - ID1: message +type Status Node + +func (n *Status) Node() *Node { return (*Node)(n) } +func (n *Status) Public() bool { return n.flags&FlagsPublic != 0 } +func (n *Status) Filename() string { return n.filename } +func (n *Status) Line() uint32 { return n.line } +func (n *Status) Keyword() t.ID { return n.id0 } +func (n *Status) Message() t.ID { return n.id1 } + +func NewStatus(flags Flags, filename string, line uint32, keyword t.ID, message t.ID) *Status { + return &Status{ + kind: KStatus, + flags: flags, + filename: filename, + line: line, + id0: keyword, + id1: message, + } +} + // Struct is "struct ID1(List0)": // - FlagsSuspendible is "ID1" vs "ID1?" // - FlagsPublic is "pub" vs "pri" @@ -581,7 +614,7 @@ func NewUse(filename string, line uint32, path t.ID) *Use { } // File is a file of source code: -// - List0: top-level declarations +// - List0: top-level declarations type File Node func (n *File) Node() *Node { return (*Node)(n) } diff --git a/lang/check/check.go b/lang/check/check.go index 433cf6c7..2c087f76 100644 --- a/lang/check/check.go +++ b/lang/check/check.go @@ -48,6 +48,13 @@ func (e *Error) Error() string { return string(b) } +func trimQuotes(s string) string { + if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' { + return s[1 : len(s)-1] + } + return s +} + // TypeExprFoo is an *ast.Node MType (implicit type). var ( TypeExprBool = a.NewTypeExpr(0, t.IDBool, nil, nil, nil) @@ -60,17 +67,22 @@ func numeric(n *a.TypeExpr) bool { return n == TypeExprIdeal || n.IsNumType() } // TypeMap maps from variable names (as token IDs) to types. type TypeMap map[t.ID]*a.TypeExpr -type Struct struct { - ID t.ID - Struct *a.Struct -} - type Func struct { - QID t.QID + QID t.QID // Qualified ID of the func name. Func *a.Func LocalVars TypeMap } +type Status struct { + ID t.ID // ID of the status message. + Status *a.Status +} + +type Struct struct { + ID t.ID // ID of the struct name. + Struct *a.Struct +} + func Check(tm *t.Map, flags Flags, files ...*a.File) (*Checker, error) { for _, f := range files { if f == nil { @@ -98,8 +110,9 @@ func Check(tm *t.Map, flags Flags, files ...*a.File) (*Checker, error) { flags: flags, tm: tm, reasonMap: rMap, - structs: map[t.ID]Struct{}, funcs: map[t.QID]Func{}, + statuses: map[t.ID]Status{}, + structs: map[t.ID]Struct{}, } for _, phase := range phases { @@ -123,6 +136,7 @@ var phases = [...]struct { check func(*Checker, *a.Node) error }{ {a.KUse, (*Checker).checkUse}, + {a.KStatus, (*Checker).checkStatus}, {a.KStruct, (*Checker).checkStruct}, {a.KFunc, (*Checker).checkFuncSignature}, {a.KFunc, (*Checker).checkFuncContract}, @@ -133,17 +147,40 @@ type Checker struct { flags Flags tm *t.Map reasonMap reasonMap - structs map[t.ID]Struct funcs map[t.QID]Func + statuses map[t.ID]Status + structs map[t.ID]Struct } -func (c *Checker) Funcs() map[t.QID]Func { return c.funcs } +func (c *Checker) Funcs() map[t.QID]Func { return c.funcs } +func (c *Checker) Statuses() map[t.ID]Status { return c.statuses } +func (c *Checker) Structs() map[t.ID]Struct { return c.structs } func (c *Checker) checkUse(node *a.Node) error { // TODO. return nil } +func (c *Checker) checkStatus(node *a.Node) error { + n := node.Status() + id := n.Message() + if other, ok := c.statuses[id]; ok { + return &Error{ + Err: fmt.Errorf("check: duplicate status %q", trimQuotes(id.String(c.tm))), + Filename: n.Filename(), + Line: n.Line(), + OtherFilename: other.Status.Filename(), + OtherLine: other.Status.Line(), + } + } + c.statuses[id] = Status{ + ID: id, + Status: n, + } + n.Node().SetTypeChecked() + return nil +} + func (c *Checker) checkFields(fields []*a.Node, banPtrTypes bool) error { if len(fields) == 0 { return nil diff --git a/lang/check/type.go b/lang/check/type.go index 23b427e0..8a56bcde 100644 --- a/lang/check/type.go +++ b/lang/check/type.go @@ -106,7 +106,15 @@ func (q *checker) tcheckStatement(n *a.Node) error { case a.KReturn: n := n.Return() - if value := n.Value(); value != nil { + if nk := n.Keyword(); nk != 0 { + if s, ok := q.c.statuses[n.Message()]; !ok { + return fmt.Errorf("check: no error or status with message %q", + trimQuotes(n.Message().String(q.tm))) + } else if sk := s.Status.Keyword(); nk != sk { + return fmt.Errorf("check: return statement says %q but declaration says %q", + nk.String(q.tm), sk.String(q.tm)) + } + } else if value := n.Value(); value != nil { if err := q.tcheckExpr(value, 0); err != nil { return err } diff --git a/lang/parse/parse.go b/lang/parse/parse.go index 0d8b5fd2..4be3b008 100644 --- a/lang/parse/parse.go +++ b/lang/parse/parse.go @@ -148,6 +148,22 @@ func (p *parser) parseTopLevelDecl() (*a.Node, error) { out := a.NewStruct(0, p.filename, line, t.IDOut, outFields) return a.NewFunc(flags, p.filename, line, id0, id1, in, out, asserts, body).Node(), nil + case t.KeyError, t.KeyStatus: + keyword := p.src[0].ID + p.src = p.src[1:] + message := p.peek1() + if !message.IsStrLiteral() { + got := p.tm.ByID(message) + return nil, fmt.Errorf(`parse: expected string literal, got %q at %s:%d`, got, p.filename, p.line()) + } + p.src = p.src[1:] + if x := p.peek1().Key(); x != t.KeySemicolon { + got := p.tm.ByKey(x) + return nil, fmt.Errorf(`parse: expected (implicit) ";", got %q at %s:%d`, got, p.filename, p.line()) + } + p.src = p.src[1:] + return a.NewStatus(flags, p.filename, line, keyword, message).Node(), nil + case t.KeyStruct: p.src = p.src[1:] name, err := p.parseIdent() @@ -515,14 +531,26 @@ func (p *parser) parseStatement1() (*a.Node, error) { case t.KeyReturn: p.src = p.src[1:] - value, err := (*a.Expr)(nil), error(nil) - if p.peek1().Key() != t.KeySemicolon { + keyword, message, value, err := t.ID(0), t.ID(0), (*a.Expr)(nil), error(nil) + switch x := p.peek1(); x.Key() { + case t.KeySemicolon: + // No-op. + case t.KeyError, t.KeyStatus: + keyword = x + p.src = p.src[1:] + message = p.peek1() + if !message.IsStrLiteral() { + got := p.tm.ByID(message) + return nil, fmt.Errorf(`parse: expected string literal, got %q at %s:%d`, got, p.filename, p.line()) + } + p.src = p.src[1:] + default: value, err = p.parseExpr() if err != nil { return nil, err } } - return a.NewReturn(value).Node(), nil + return a.NewReturn(keyword, message, value).Node(), nil case t.KeyVar: p.src = p.src[1:] diff --git a/lang/token/list.go b/lang/token/list.go index 3c689241..15aa2f39 100644 --- a/lang/token/list.go +++ b/lang/token/list.go @@ -207,6 +207,8 @@ const ( KeyVia = Key(IDVia >> KeyShift) KeyPub = Key(IDPub >> KeyShift) KeyPri = Key(IDPri >> KeyShift) + KeyError = Key(IDError >> KeyShift) + KeyStatus = Key(IDStatus >> KeyShift) KeyFalse = Key(IDFalse >> KeyShift) KeyTrue = Key(IDTrue >> KeyShift) @@ -356,6 +358,8 @@ const ( IDVia = ID(0x70<