diff --git a/cmd/wuffs/gen.go b/cmd/wuffs/gen.go index 836a42c7..6aa685c7 100644 --- a/cmd/wuffs/gen.go +++ b/cmd/wuffs/gen.go @@ -314,11 +314,20 @@ func (h *genHelper) genWuffs(dirname string, qualifiedFilenames []string) error if !n.Public() { continue } - classy := "" + fmt.Fprintf(out, "pub struct %s", n.QID().Str(&h.tm)) if n.Classy() { - classy = "?" + fmt.Fprintf(out, "?") } - fmt.Fprintf(out, "pub struct %s%s()\n", n.QID().Str(&h.tm), classy) + if imps := n.Implements(); len(imps) > 0 { + fmt.Fprintf(out, " implements ") + for i, imp := range imps { + if i > 0 { + fmt.Fprintf(out, ", ") + } + fmt.Fprintf(out, "%s", imp.AsTypeExpr().Str(&h.tm)) + } + } + fmt.Fprintf(out, "()\n") } } } diff --git a/lang/ast/ast.go b/lang/ast/ast.go index 814b84b0..fdbb5464 100644 --- a/lang/ast/ast.go +++ b/lang/ast/ast.go @@ -891,32 +891,35 @@ func NewConst(flags Flags, filename string, line uint32, name t.ID, xType *TypeE // implement. const MaxImplements = 63 -// Struct is "struct ID2?(List1)": +// Struct is "struct ID2? implements List0 (List1)": // - FlagsPublic is "pub" vs "pri" // - FlagsClassy is "ID2" vs "ID2?" // - ID1: <0|pkg> (set by calling SetPackage) // - ID2: name +// - List0: implements // - List1: fields // // The question mark indicates a classy struct - one that supports methods, // especially coroutines. type Struct Node -func (n *Struct) AsNode() *Node { return (*Node)(n) } -func (n *Struct) Classy() bool { return n.flags&FlagsClassy != 0 } -func (n *Struct) Public() bool { return n.flags&FlagsPublic != 0 } -func (n *Struct) Filename() string { return n.filename } -func (n *Struct) Line() uint32 { return n.line } -func (n *Struct) QID() t.QID { return t.QID{n.id1, n.id2} } -func (n *Struct) Fields() []*Node { return n.list1 } +func (n *Struct) AsNode() *Node { return (*Node)(n) } +func (n *Struct) Classy() bool { return n.flags&FlagsClassy != 0 } +func (n *Struct) Public() bool { return n.flags&FlagsPublic != 0 } +func (n *Struct) Filename() string { return n.filename } +func (n *Struct) Line() uint32 { return n.line } +func (n *Struct) QID() t.QID { return t.QID{n.id1, n.id2} } +func (n *Struct) Implements() []*Node { return n.list0 } +func (n *Struct) Fields() []*Node { return n.list1 } -func NewStruct(flags Flags, filename string, line uint32, name t.ID, fields []*Node) *Struct { +func NewStruct(flags Flags, filename string, line uint32, name t.ID, implements []*Node, fields []*Node) *Struct { return &Struct{ kind: KStruct, flags: flags, filename: filename, line: line, id2: name, + list0: implements, list1: fields, } } diff --git a/lang/builtin/builtin.go b/lang/builtin/builtin.go index 3e57af21..773a60d7 100644 --- a/lang/builtin/builtin.go +++ b/lang/builtin/builtin.go @@ -347,6 +347,10 @@ var Interfaces = []string{ "hasher_u32", } +var InterfacesMap = map[string]bool{ + "hasher_u32": true, +} + var InterfaceFuncs = []string{ // ---- hasher_u32 diff --git a/lang/check/check.go b/lang/check/check.go index 5c82f7a2..445879e0 100644 --- a/lang/check/check.go +++ b/lang/check/check.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "path" + "sort" "github.com/google/wuffs/lang/builtin" "github.com/google/wuffs/lang/parse" @@ -83,29 +84,48 @@ func Check(tm *t.Map, files []*a.File, resolveUse func(usePath string) ([]byte, } } c := &Checker{ - tm: tm, - resolveUse: resolveUse, - reasonMap: rMap, - consts: map[t.QID]*a.Const{}, - funcs: map[t.QQID]*a.Func{}, - localVars: map[t.QQID]typeMap{}, - statuses: map[t.QID]*a.Status{}, - structs: map[t.QID]*a.Struct{}, + tm: tm, + resolveUse: resolveUse, + reasonMap: rMap, + + consts: map[t.QID]*a.Const{}, + funcs: map[t.QQID]*a.Func{}, + localVars: map[t.QQID]typeMap{}, + statuses: map[t.QID]*a.Status{}, + structs: map[t.QID]*a.Struct{}, + useBaseNames: map[t.ID]struct{}{}, + + builtInSliceFuncs: map[t.QQID]*a.Func{}, + builtInTableFuncs: map[t.QQID]*a.Func{}, + + builtInInterfaces: map[t.QID][]t.QQID{}, + builtInInterfaceFuncs: map[t.QQID]*a.Func{}, + unseenInterfaceImpls: map[t.QQID]*a.Func{}, } - _, err := c.parseBuiltInFuncs(builtin.Funcs, false) - if err != nil { + if err := c.parseBuiltInFuncs(nil, builtin.Funcs, false); err != nil { return nil, err } - c.builtInSliceFuncs, err = c.parseBuiltInFuncs(builtin.SliceFuncs, true) - if err != nil { + if err := c.parseBuiltInFuncs(c.builtInSliceFuncs, builtin.SliceFuncs, true); err != nil { return nil, err } - c.builtInTableFuncs, err = c.parseBuiltInFuncs(builtin.TableFuncs, true) - if err != nil { + if err := c.parseBuiltInFuncs(c.builtInTableFuncs, builtin.TableFuncs, true); err != nil { return nil, err } + if err := c.parseBuiltInFuncs(c.builtInInterfaceFuncs, builtin.InterfaceFuncs, false); err != nil { + return nil, err + } + + for qqid := range c.builtInInterfaceFuncs { + qid := t.QID{qqid[0], qqid[1]} + c.builtInInterfaces[qid] = append(c.builtInInterfaces[qid], qqid) + } + for _, qqids := range c.builtInInterfaces { + sort.Slice(qqids, func(i int, j int) bool { + return qqids[i].LessThan(qqids[j]) + }) + } for _, z := range builtin.Statuses { id, err := tm.Insert(z) @@ -150,7 +170,9 @@ var phases = [...]struct { {a.KStruct, (*Checker).checkStructFields}, {a.KFunc, (*Checker).checkFuncSignature}, {a.KFunc, (*Checker).checkFuncContract}, + {a.KFunc, (*Checker).checkFuncImplements}, {a.KFunc, (*Checker).checkFuncBody}, + {a.KInvalid, (*Checker).checkInterfacesSatisfied}, {a.KStruct, (*Checker).checkFieldMethodCollisions}, {a.KInvalid, (*Checker).checkAllTypeChecked}, // TODO: check consts, funcs, structs and uses for name collisions. @@ -177,7 +199,12 @@ type Checker struct { builtInSliceFuncs map[t.QQID]*a.Func builtInTableFuncs map[t.QQID]*a.Func - unsortedStructs []*a.Struct + + builtInInterfaces map[t.QID][]t.QQID + builtInInterfaceFuncs map[t.QQID]*a.Func + unseenInterfaceImpls map[t.QQID]*a.Func + + unsortedStructs []*a.Struct } func (c *Checker) checkUse(node *a.Node) error { @@ -327,7 +354,7 @@ func (c *Checker) checkConstElement(n *a.Expr, nb bounds, nLists int) error { return nil } if cv := n.ConstValue(); cv == nil || cv.Cmp(nb[0]) < 0 || cv.Cmp(nb[1]) > 0 { - return fmt.Errorf("invalid const value %q not within %v", n.Str(c.tm), nb) + return fmt.Errorf("check: invalid const value %q not within %v", n.Str(c.tm), nb) } return nil } @@ -348,8 +375,37 @@ func (c *Checker) checkStructDecl(node *a.Node) error { c.unsortedStructs = append(c.unsortedStructs, n) setPlaceholderMBoundsMType(n.AsNode()) + // Add entries to c.unseenInterfaceImpls that later stages remove, checking + // that the concrete type (in this package) actually implements the + // interfaces that it claims to. + for _, o := range n.Implements() { + // For example, qid and ifaceType could be "<>.hasher" (i.e. defined in + // this package, not the base package) and "base.hasher_u32". + // + // The "<>" denotes an empty element of a t.QID or t.QQID. + o := o.AsTypeExpr() + ifaceType := o.QID() + + if (o.Decorator() != 0) || (ifaceType[0] != t.IDBase) || + !builtin.InterfacesMap[ifaceType[1].Str(c.tm)] { + return fmt.Errorf("check: invalid interface type %q", o.Str(c.tm)) + } + o.AsNode().SetMBounds(bounds{zero, zero}) + o.AsNode().SetMType(typeExprTypeExpr) + + if qid[0] != 0 { + continue + } + for _, ifaceFunc := range c.builtInInterfaces[ifaceType] { + // Continuing the example, ifaceFunc could be + // "base.hasher_u32.update_u32". + c.unseenInterfaceImpls[t.QQID{qid[0], qid[1], ifaceFunc[2]}] = + c.builtInInterfaceFuncs[ifaceFunc] + } + } + // A struct declaration implies a reset method. - in := a.NewStruct(0, n.Filename(), n.Line(), t.IDArgs, nil) + in := a.NewStruct(0, n.Filename(), n.Line(), t.IDArgs, nil, nil) f := a.NewFunc(a.EffectImpure.AsFlags(), n.Filename(), n.Line(), qid[1], t.IDReset, in, nil, nil, nil) if qid[0] != 0 { f.AsNode().AsRaw().SetPackage(c.tm, qid[0]) @@ -529,6 +585,37 @@ func (c *Checker) checkFuncContract(node *a.Node) error { return nil } +func (c *Checker) checkFuncImplements(node *a.Node) error { + n := node.AsFunc() + o := c.unseenInterfaceImpls[n.QQID()] + if o == nil { + return nil + } + + if (n.Effect() != o.Effect()) || !n.Out().Eq(o.Out()) { + return nil + } + + // Check that the args (the implicit In types) match. + nArgs := n.In().Fields() + oArgs := o.In().Fields() + if len(nArgs) != len(oArgs) { + return nil + } + for i := range nArgs { + na := nArgs[i].AsField() + oa := oArgs[i].AsField() + if na.Name() != oa.Name() || !na.XType().Eq(oa.XType()) { + return nil + } + } + + // TODO: check that n.Asserts() matches o.Asserts(). + + delete(c.unseenInterfaceImpls, n.QQID()) + return nil +} + func (c *Checker) checkFuncBody(node *a.Node) error { n := node.AsFunc() if len(n.Body()) == 0 { @@ -577,6 +664,30 @@ func (c *Checker) checkFuncBody(node *a.Node) error { return nil } +func (c *Checker) checkInterfacesSatisfied(node *a.Node) error { + if len(c.unseenInterfaceImpls) == 0 { + return nil + } + + // Pick the largest t.QQID key, despite randomized map iteration order, for + // deterministic error messages. The zero-valued t.QQID is LessThan any + // non-zero value. + method, iface := t.QQID{}, t.QID{} + for qqid, f := range c.unseenInterfaceImpls { + if method.LessThan(qqid) { + fqqid := f.QQID() + method, iface = qqid, t.QID{fqqid[0], fqqid[1]} + } + } + // For example, at the end of the loop above, method and iface could be + // "<>.hasher.update_u32" and "base.hasher_u32". + // + // The "<>" denotes an empty element of a t.QID or t.QQID. + + return fmt.Errorf("check: %q does not implement %q: no matching %q method", + method[1].Str(c.tm), iface.Str(c.tm), method[2].Str(c.tm)) +} + func (c *Checker) checkFieldMethodCollisions(node *a.Node) error { n := node.AsStruct() for _, o := range n.Fields() { diff --git a/lang/check/resolve.go b/lang/check/resolve.go index 88eeb59a..8c8a3714 100644 --- a/lang/check/resolve.go +++ b/lang/check/resolve.go @@ -110,13 +110,8 @@ var builtInTypeMap = typeMap{ t.IDDecodeFrameOptions: typeExprDecodeFrameOptions, } -func (c *Checker) parseBuiltInFuncs(ss []string, generic bool) (map[t.QQID]*a.Func, error) { - m := map[t.QQID]*a.Func(nil) - if generic { - m = map[t.QQID]*a.Func{} - } - - if err := builtin.ParseFuncs(c.tm, ss, generic, func(f *a.Func) error { +func (c *Checker) parseBuiltInFuncs(m map[t.QQID]*a.Func, ss []string, generic bool) error { + return builtin.ParseFuncs(c.tm, ss, generic, func(f *a.Func) error { if err := c.checkFuncSignature(f.AsNode()); err != nil { return err } @@ -124,11 +119,7 @@ func (c *Checker) parseBuiltInFuncs(ss []string, generic bool) (map[t.QQID]*a.Fu m[f.QQID()] = f } return nil - }); err != nil { - return nil, err - } - - return m, nil + }) } func (c *Checker) resolveFunc(typ *a.TypeExpr) (*a.Func, error) { diff --git a/lang/parse/parse.go b/lang/parse/parse.go index 050b2cbe..2de086a9 100644 --- a/lang/parse/parse.go +++ b/lang/parse/parse.go @@ -217,7 +217,7 @@ func (p *parser) parseTopLevelDecl() (*a.Node, error) { } p.src = p.src[1:] p.funcEffect = 0 - in := a.NewStruct(0, p.filename, line, t.IDArgs, argFields) + in := a.NewStruct(0, p.filename, line, t.IDArgs, nil, argFields) return a.NewFunc(flags, p.filename, line, id0, id1, in, out, asserts, body).AsNode(), nil case t.IDStatus: @@ -255,6 +255,16 @@ func (p *parser) parseTopLevelDecl() (*a.Node, error) { flags |= a.FlagsClassy p.src = p.src[1:] } + + implements := []*a.Node(nil) + if p.peek1() == t.IDImplements { + p.src = p.src[1:] + implements, err = p.parseList(t.IDOpenParen, (*parser).parseQualifiedIdentNode) + if err != nil { + return nil, err + } + } + fields, err := p.parseList(t.IDCloseParen, (*parser).parseFieldNode) if err != nil { return nil, err @@ -271,12 +281,20 @@ func (p *parser) parseTopLevelDecl() (*a.Node, error) { return nil, fmt.Errorf(`parse: expected (implicit) ";", got %q at %s:%d`, got, p.filename, p.line()) } p.src = p.src[1:] - return a.NewStruct(flags, p.filename, line, name, fields).AsNode(), nil + return a.NewStruct(flags, p.filename, line, name, implements, fields).AsNode(), nil } } return nil, fmt.Errorf(`parse: unrecognized top level declaration at %s:%d`, p.filename, line) } +func (p *parser) parseQualifiedIdentNode() (*a.Node, error) { + pkg, name, err := p.parseQualifiedIdent() + if err != nil { + return nil, err + } + return a.NewTypeExpr(0, pkg, name, nil, nil, nil).AsNode(), nil +} + // parseQualifiedIdent parses "foo.bar" or "bar". func (p *parser) parseQualifiedIdent() (t.ID, t.ID, error) { x, err := p.parseIdent() diff --git a/lang/render/render.go b/lang/render/render.go index 1265dd6c..b09cf0a7 100644 --- a/lang/render/render.go +++ b/lang/render/render.go @@ -147,7 +147,7 @@ func Render(w io.Writer, tm *t.Map, src []t.Token, comments []string) (err error if prevID == t.IDEq || (prevID != 0 && !prevIsTightRight && !tok.ID.IsTightLeft()) { // The "(" token's tight-left-ness is context dependent. For // "f(x)", the "(" is tight-left. For "a * (b + c)", it is not. - if tok.ID != t.IDOpenParen || !isCloseIdentStrLiteral(tm, prevID) { + if tok.ID != t.IDOpenParen || !isCloseIdentStrLiteralQuestion(tm, prevID) { buf = append(buf, ' ') } } @@ -164,8 +164,6 @@ func Render(w io.Writer, tm *t.Map, src []t.Token, comments []string) (err error return errors.New("render: too many \"}\" tokens") } indent-- - } else if (tok.ID == t.IDQuestion) && (prevID == t.IDYield) { - buf = append(buf, ' ') } prevIsTightRight = tok.ID.IsTightRight() @@ -248,8 +246,8 @@ func isCloseIdentLiteral(tm *t.Map, x t.ID) bool { return x.IsClose() || x.IsIdent(tm) || x.IsLiteral(tm) } -func isCloseIdentStrLiteral(tm *t.Map, x t.ID) bool { - return x.IsClose() || x.IsIdent(tm) || x.IsStrLiteral(tm) +func isCloseIdentStrLiteralQuestion(tm *t.Map, x t.ID) bool { + return x.IsClose() || x.IsIdent(tm) || x.IsStrLiteral(tm) || (x == t.IDQuestion) } func measureVarNameLength(tm *t.Map, lineTokens []t.Token, remaining []t.Token) uint32 { diff --git a/lang/token/list.go b/lang/token/list.go index 5393ade0..10c1c849 100644 --- a/lang/token/list.go +++ b/lang/token/list.go @@ -149,6 +149,13 @@ type QID [2]ID func (x QID) IsZero() bool { return x == QID{} } +func (x QID) LessThan(y QID) bool { + if x[0] != y[0] { + return x[0] < y[0] + } + return x[1] < y[1] +} + // Str returns a string form of x. func (x QID) Str(m *Map) string { if x[0] != 0 { @@ -162,6 +169,16 @@ type QQID [3]ID func (x QQID) IsZero() bool { return x == QQID{} } +func (x QQID) LessThan(y QQID) bool { + if x[0] != y[0] { + return x[0] < y[0] + } + if x[1] != y[1] { + return x[1] < y[1] + } + return x[2] < y[2] +} + // Str returns a string form of x. func (x QQID) Str(m *Map) string { if x[0] != 0 { @@ -344,28 +361,29 @@ const ( minKeyword = 0xA0 maxKeyword = 0xBF - IDAssert = ID(0xA0) - IDBreak = ID(0xA1) - IDConst = ID(0xA2) - IDContinue = ID(0xA3) - IDElse = ID(0xA4) - IDFunc = ID(0xA5) - IDIOBind = ID(0xA6) - IDIOLimit = ID(0xA7) - IDIf = ID(0xA8) - IDInv = ID(0xA9) - IDIterate = ID(0xAA) - IDPost = ID(0xAB) - IDPre = ID(0xAC) - IDPri = ID(0xAD) - IDPub = ID(0xAE) - IDReturn = ID(0xAF) - IDStruct = ID(0xB0) - IDUse = ID(0xB1) - IDVar = ID(0xB2) - IDVia = ID(0xB3) - IDWhile = ID(0xB4) - IDYield = ID(0xB5) + IDAssert = ID(0xA0) + IDBreak = ID(0xA1) + IDConst = ID(0xA2) + IDContinue = ID(0xA3) + IDElse = ID(0xA4) + IDFunc = ID(0xA5) + IDIOBind = ID(0xA6) + IDIOLimit = ID(0xA7) + IDIf = ID(0xA8) + IDImplements = ID(0xA9) + IDInv = ID(0xAA) + IDIterate = ID(0xAB) + IDPost = ID(0xAC) + IDPre = ID(0xAD) + IDPri = ID(0xAE) + IDPub = ID(0xAF) + IDReturn = ID(0xB0) + IDStruct = ID(0xB1) + IDUse = ID(0xB2) + IDVar = ID(0xB3) + IDVia = ID(0xB4) + IDWhile = ID(0xB5) + IDYield = ID(0xB6) ) const ( @@ -687,28 +705,29 @@ var builtInsByID = [nBuiltInIDs]string{ IDNot: "not", - IDAssert: "assert", - IDBreak: "break", - IDConst: "const", - IDContinue: "continue", - IDElse: "else", - IDFunc: "func", - IDIOBind: "io_bind", - IDIOLimit: "io_limit", - IDIf: "if", - IDInv: "inv", - IDIterate: "iterate", - IDPost: "post", - IDPre: "pre", - IDPri: "pri", - IDPub: "pub", - IDReturn: "return", - IDStruct: "struct", - IDUse: "use", - IDVar: "var", - IDVia: "via", - IDWhile: "while", - IDYield: "yield", + IDAssert: "assert", + IDBreak: "break", + IDConst: "const", + IDContinue: "continue", + IDElse: "else", + IDFunc: "func", + IDIOBind: "io_bind", + IDIOLimit: "io_limit", + IDIf: "if", + IDImplements: "implements", + IDInv: "inv", + IDIterate: "iterate", + IDPost: "post", + IDPre: "pre", + IDPri: "pri", + IDPub: "pub", + IDReturn: "return", + IDStruct: "struct", + IDUse: "use", + IDVar: "var", + IDVia: "via", + IDWhile: "while", + IDYield: "yield", IDArray: "array", IDNptr: "nptr", @@ -1207,7 +1226,6 @@ var isTightRight = [...]bool{ IDOpenParen: true, IDOpenBracket: true, - IDDot: true, - IDExclam: true, - IDQuestion: true, + IDDot: true, + IDExclam: true, } diff --git a/std/adler32/common_adler32.wuffs b/std/adler32/common_adler32.wuffs index c9dfa1e1..b3366179 100644 --- a/std/adler32/common_adler32.wuffs +++ b/std/adler32/common_adler32.wuffs @@ -13,7 +13,7 @@ // limitations under the License. // TODO: drop the '?' but still generate wuffs_adler32__hasher__initialize? -pub struct hasher?( +pub struct hasher? implements base.hasher_u32( state : base.u32, started : base.bool, ) diff --git a/std/crc32/common_crc32.wuffs b/std/crc32/common_crc32.wuffs index 1f4bad21..effef3f8 100644 --- a/std/crc32/common_crc32.wuffs +++ b/std/crc32/common_crc32.wuffs @@ -13,7 +13,7 @@ // limitations under the License. // TODO: drop the '?' but still generate wuffs_crc32__ieee_hasher__initialize? -pub struct ieee_hasher?( +pub struct ieee_hasher? implements base.hasher_u32( state : base.u32, )