diff --git a/go.mod b/go.mod index 1e55cca74..62e88627c 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ go 1.23 replace github.com/go-swagger/go-swagger => github.com/superseriousbusiness/go-swagger v0.31.0-gts-go1.23-fix // Replace modernc/sqlite with our version that fixes the concurrency INTERRUPT issue -replace modernc.org/sqlite => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.2-concurrency-workaround +replace modernc.org/sqlite => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.5-concurrency-workaround // Below pin otel libraries to v1.29.0 until we can figure out issues replace go.opentelemetry.io/otel => go.opentelemetry.io/otel v1.29.0 @@ -161,7 +161,6 @@ require ( github.com/gorilla/securecookie v1.1.2 // indirect github.com/gorilla/sessions v1.2.2 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect - github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/huandu/xstrings v1.4.0 // indirect github.com/imdario/mergo v0.3.16 // indirect @@ -235,10 +234,7 @@ require ( google.golang.org/protobuf v1.36.2 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect modernc.org/memory v1.8.0 // indirect - modernc.org/strutil v1.2.0 // indirect - modernc.org/token v1.1.0 // indirect ) diff --git a/go.sum b/go.sum index 0c93489a5..da8694bd8 100644 --- a/go.sum +++ b/go.sum @@ -328,8 +328,6 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjw github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= -github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= @@ -615,8 +613,8 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= -gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.2-concurrency-workaround h1:Z/9vgdPNZm8ZDANnIJ7ZGeYKJ5biqPY1OQbN+DLCtec= -gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.2-concurrency-workaround/go.mod h1:dnR723UrTtjKpoHCAMN0Q/gZ9MT4r+iRvIBb9umWFkU= +gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.5-concurrency-workaround h1:BLmmUkkZ2KiS8k2lePZRQo7Z5puFrfxuFq9BrJQmS9o= +gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.5-concurrency-workaround/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80= go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= @@ -1012,8 +1010,6 @@ modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= -modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= -modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= diff --git a/vendor/github.com/hashicorp/golang-lru/v2/.gitignore b/vendor/github.com/hashicorp/golang-lru/v2/.gitignore deleted file mode 100644 index 836562412..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test diff --git a/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml b/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml deleted file mode 100644 index 7e7b8a962..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright (c) HashiCorp, Inc. -# SPDX-License-Identifier: MPL-2.0 - -linters: - fast: false - disable-all: true - enable: - - revive - - megacheck - - govet - - unconvert - - gas - - gocyclo - - dupl - - misspell - - unparam - - unused - - typecheck - - ineffassign - # - stylecheck - - exportloopref - - gocritic - - nakedret - - gosimple - - prealloc - -# golangci-lint configuration file -linters-settings: - revive: - ignore-generated-header: true - severity: warning - rules: - - name: package-comments - severity: warning - disabled: true - - name: exported - severity: warning - disabled: false - arguments: ["checkPrivateReceivers", "disableStutteringCheck"] - -issues: - exclude-use-default: false - exclude-rules: - - path: _test\.go - linters: - - dupl diff --git a/vendor/github.com/hashicorp/golang-lru/v2/2q.go b/vendor/github.com/hashicorp/golang-lru/v2/2q.go deleted file mode 100644 index 8c95252b6..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/2q.go +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package lru - -import ( - "errors" - "sync" - - "github.com/hashicorp/golang-lru/v2/simplelru" -) - -const ( - // Default2QRecentRatio is the ratio of the 2Q cache dedicated - // to recently added entries that have only been accessed once. - Default2QRecentRatio = 0.25 - - // Default2QGhostEntries is the default ratio of ghost - // entries kept to track entries recently evicted - Default2QGhostEntries = 0.50 -) - -// TwoQueueCache is a thread-safe fixed size 2Q cache. -// 2Q is an enhancement over the standard LRU cache -// in that it tracks both frequently and recently used -// entries separately. This avoids a burst in access to new -// entries from evicting frequently used entries. It adds some -// additional tracking overhead to the standard LRU cache, and is -// computationally about 2x the cost, and adds some metadata over -// head. The ARCCache is similar, but does not require setting any -// parameters. -type TwoQueueCache[K comparable, V any] struct { - size int - recentSize int - recentRatio float64 - ghostRatio float64 - - recent simplelru.LRUCache[K, V] - frequent simplelru.LRUCache[K, V] - recentEvict simplelru.LRUCache[K, struct{}] - lock sync.RWMutex -} - -// New2Q creates a new TwoQueueCache using the default -// values for the parameters. -func New2Q[K comparable, V any](size int) (*TwoQueueCache[K, V], error) { - return New2QParams[K, V](size, Default2QRecentRatio, Default2QGhostEntries) -} - -// New2QParams creates a new TwoQueueCache using the provided -// parameter values. -func New2QParams[K comparable, V any](size int, recentRatio, ghostRatio float64) (*TwoQueueCache[K, V], error) { - if size <= 0 { - return nil, errors.New("invalid size") - } - if recentRatio < 0.0 || recentRatio > 1.0 { - return nil, errors.New("invalid recent ratio") - } - if ghostRatio < 0.0 || ghostRatio > 1.0 { - return nil, errors.New("invalid ghost ratio") - } - - // Determine the sub-sizes - recentSize := int(float64(size) * recentRatio) - evictSize := int(float64(size) * ghostRatio) - - // Allocate the LRUs - recent, err := simplelru.NewLRU[K, V](size, nil) - if err != nil { - return nil, err - } - frequent, err := simplelru.NewLRU[K, V](size, nil) - if err != nil { - return nil, err - } - recentEvict, err := simplelru.NewLRU[K, struct{}](evictSize, nil) - if err != nil { - return nil, err - } - - // Initialize the cache - c := &TwoQueueCache[K, V]{ - size: size, - recentSize: recentSize, - recentRatio: recentRatio, - ghostRatio: ghostRatio, - recent: recent, - frequent: frequent, - recentEvict: recentEvict, - } - return c, nil -} - -// Get looks up a key's value from the cache. -func (c *TwoQueueCache[K, V]) Get(key K) (value V, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if this is a frequent value - if val, ok := c.frequent.Get(key); ok { - return val, ok - } - - // If the value is contained in recent, then we - // promote it to frequent - if val, ok := c.recent.Peek(key); ok { - c.recent.Remove(key) - c.frequent.Add(key, val) - return val, ok - } - - // No hit - return -} - -// Add adds a value to the cache. -func (c *TwoQueueCache[K, V]) Add(key K, value V) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if the value is frequently used already, - // and just update the value - if c.frequent.Contains(key) { - c.frequent.Add(key, value) - return - } - - // Check if the value is recently used, and promote - // the value into the frequent list - if c.recent.Contains(key) { - c.recent.Remove(key) - c.frequent.Add(key, value) - return - } - - // If the value was recently evicted, add it to the - // frequently used list - if c.recentEvict.Contains(key) { - c.ensureSpace(true) - c.recentEvict.Remove(key) - c.frequent.Add(key, value) - return - } - - // Add to the recently seen list - c.ensureSpace(false) - c.recent.Add(key, value) -} - -// ensureSpace is used to ensure we have space in the cache -func (c *TwoQueueCache[K, V]) ensureSpace(recentEvict bool) { - // If we have space, nothing to do - recentLen := c.recent.Len() - freqLen := c.frequent.Len() - if recentLen+freqLen < c.size { - return - } - - // If the recent buffer is larger than - // the target, evict from there - if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) { - k, _, _ := c.recent.RemoveOldest() - c.recentEvict.Add(k, struct{}{}) - return - } - - // Remove from the frequent list otherwise - c.frequent.RemoveOldest() -} - -// Len returns the number of items in the cache. -func (c *TwoQueueCache[K, V]) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.recent.Len() + c.frequent.Len() -} - -// Resize changes the cache size. -func (c *TwoQueueCache[K, V]) Resize(size int) (evicted int) { - c.lock.Lock() - defer c.lock.Unlock() - - // Recalculate the sub-sizes - recentSize := int(float64(size) * c.recentRatio) - evictSize := int(float64(size) * c.ghostRatio) - c.size = size - c.recentSize = recentSize - - // ensureSpace - diff := c.recent.Len() + c.frequent.Len() - size - if diff < 0 { - diff = 0 - } - for i := 0; i < diff; i++ { - c.ensureSpace(true) - } - - // Reallocate the LRUs - c.recent.Resize(size) - c.frequent.Resize(size) - c.recentEvict.Resize(evictSize) - - return diff -} - -// Keys returns a slice of the keys in the cache. -// The frequently used keys are first in the returned slice. -func (c *TwoQueueCache[K, V]) Keys() []K { - c.lock.RLock() - defer c.lock.RUnlock() - k1 := c.frequent.Keys() - k2 := c.recent.Keys() - return append(k1, k2...) -} - -// Values returns a slice of the values in the cache. -// The frequently used values are first in the returned slice. -func (c *TwoQueueCache[K, V]) Values() []V { - c.lock.RLock() - defer c.lock.RUnlock() - v1 := c.frequent.Values() - v2 := c.recent.Values() - return append(v1, v2...) -} - -// Remove removes the provided key from the cache. -func (c *TwoQueueCache[K, V]) Remove(key K) { - c.lock.Lock() - defer c.lock.Unlock() - if c.frequent.Remove(key) { - return - } - if c.recent.Remove(key) { - return - } - if c.recentEvict.Remove(key) { - return - } -} - -// Purge is used to completely clear the cache. -func (c *TwoQueueCache[K, V]) Purge() { - c.lock.Lock() - defer c.lock.Unlock() - c.recent.Purge() - c.frequent.Purge() - c.recentEvict.Purge() -} - -// Contains is used to check if the cache contains a key -// without updating recency or frequency. -func (c *TwoQueueCache[K, V]) Contains(key K) bool { - c.lock.RLock() - defer c.lock.RUnlock() - return c.frequent.Contains(key) || c.recent.Contains(key) -} - -// Peek is used to inspect the cache value of a key -// without updating recency or frequency. -func (c *TwoQueueCache[K, V]) Peek(key K) (value V, ok bool) { - c.lock.RLock() - defer c.lock.RUnlock() - if val, ok := c.frequent.Peek(key); ok { - return val, ok - } - return c.recent.Peek(key) -} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/LICENSE b/vendor/github.com/hashicorp/golang-lru/v2/LICENSE deleted file mode 100644 index 0e5d580e0..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/LICENSE +++ /dev/null @@ -1,364 +0,0 @@ -Copyright (c) 2014 HashiCorp, Inc. - -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/golang-lru/v2/README.md b/vendor/github.com/hashicorp/golang-lru/v2/README.md deleted file mode 100644 index a942eb539..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/README.md +++ /dev/null @@ -1,79 +0,0 @@ -golang-lru -========== - -This provides the `lru` package which implements a fixed-size -thread safe LRU cache. It is based on the cache in Groupcache. - -Documentation -============= - -Full docs are available on [Go Packages](https://pkg.go.dev/github.com/hashicorp/golang-lru/v2) - -LRU cache example -================= - -```go -package main - -import ( - "fmt" - "github.com/hashicorp/golang-lru/v2" -) - -func main() { - l, _ := lru.New[int, any](128) - for i := 0; i < 256; i++ { - l.Add(i, nil) - } - if l.Len() != 128 { - panic(fmt.Sprintf("bad len: %v", l.Len())) - } -} -``` - -Expirable LRU cache example -=========================== - -```go -package main - -import ( - "fmt" - "time" - - "github.com/hashicorp/golang-lru/v2/expirable" -) - -func main() { - // make cache with 10ms TTL and 5 max keys - cache := expirable.NewLRU[string, string](5, nil, time.Millisecond*10) - - - // set value under key1. - cache.Add("key1", "val1") - - // get value under key1 - r, ok := cache.Get("key1") - - // check for OK value - if ok { - fmt.Printf("value before expiration is found: %v, value: %q\n", ok, r) - } - - // wait for cache to expire - time.Sleep(time.Millisecond * 12) - - // get value under key1 after key expiration - r, ok = cache.Get("key1") - fmt.Printf("value after expiration is found: %v, value: %q\n", ok, r) - - // set value under key2, would evict old entry because it is already expired. - cache.Add("key2", "val2") - - fmt.Printf("Cache len: %d\n", cache.Len()) - // Output: - // value before expiration is found: true, value: "val1" - // value after expiration is found: false, value: "" - // Cache len: 1 -} -``` diff --git a/vendor/github.com/hashicorp/golang-lru/v2/doc.go b/vendor/github.com/hashicorp/golang-lru/v2/doc.go deleted file mode 100644 index 24107ee0e..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/doc.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -// Package lru provides three different LRU caches of varying sophistication. -// -// Cache is a simple LRU cache. It is based on the LRU implementation in -// groupcache: https://github.com/golang/groupcache/tree/master/lru -// -// TwoQueueCache tracks frequently used and recently used entries separately. -// This avoids a burst of accesses from taking out frequently used entries, at -// the cost of about 2x computational overhead and some extra bookkeeping. -// -// ARCCache is an adaptive replacement cache. It tracks recent evictions as well -// as recent usage in both the frequent and recent caches. Its computational -// overhead is comparable to TwoQueueCache, but the memory overhead is linear -// with the size of the cache. -// -// ARC has been patented by IBM, so do not use it if that is problematic for -// your program. For this reason, it is in a separate go module contained within -// this repository. -// -// All caches in this package take locks while operating, and are therefore -// thread-safe for consumers. -package lru diff --git a/vendor/github.com/hashicorp/golang-lru/v2/internal/list.go b/vendor/github.com/hashicorp/golang-lru/v2/internal/list.go deleted file mode 100644 index 5cd74a034..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/internal/list.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE_list file. - -package internal - -import "time" - -// Entry is an LRU Entry -type Entry[K comparable, V any] struct { - // Next and previous pointers in the doubly-linked list of elements. - // To simplify the implementation, internally a list l is implemented - // as a ring, such that &l.root is both the next element of the last - // list element (l.Back()) and the previous element of the first list - // element (l.Front()). - next, prev *Entry[K, V] - - // The list to which this element belongs. - list *LruList[K, V] - - // The LRU Key of this element. - Key K - - // The Value stored with this element. - Value V - - // The time this element would be cleaned up, optional - ExpiresAt time.Time - - // The expiry bucket item was put in, optional - ExpireBucket uint8 -} - -// PrevEntry returns the previous list element or nil. -func (e *Entry[K, V]) PrevEntry() *Entry[K, V] { - if p := e.prev; e.list != nil && p != &e.list.root { - return p - } - return nil -} - -// LruList represents a doubly linked list. -// The zero Value for LruList is an empty list ready to use. -type LruList[K comparable, V any] struct { - root Entry[K, V] // sentinel list element, only &root, root.prev, and root.next are used - len int // current list Length excluding (this) sentinel element -} - -// Init initializes or clears list l. -func (l *LruList[K, V]) Init() *LruList[K, V] { - l.root.next = &l.root - l.root.prev = &l.root - l.len = 0 - return l -} - -// NewList returns an initialized list. -func NewList[K comparable, V any]() *LruList[K, V] { return new(LruList[K, V]).Init() } - -// Length returns the number of elements of list l. -// The complexity is O(1). -func (l *LruList[K, V]) Length() int { return l.len } - -// Back returns the last element of list l or nil if the list is empty. -func (l *LruList[K, V]) Back() *Entry[K, V] { - if l.len == 0 { - return nil - } - return l.root.prev -} - -// lazyInit lazily initializes a zero List Value. -func (l *LruList[K, V]) lazyInit() { - if l.root.next == nil { - l.Init() - } -} - -// insert inserts e after at, increments l.len, and returns e. -func (l *LruList[K, V]) insert(e, at *Entry[K, V]) *Entry[K, V] { - e.prev = at - e.next = at.next - e.prev.next = e - e.next.prev = e - e.list = l - l.len++ - return e -} - -// insertValue is a convenience wrapper for insert(&Entry{Value: v, ExpiresAt: ExpiresAt}, at). -func (l *LruList[K, V]) insertValue(k K, v V, expiresAt time.Time, at *Entry[K, V]) *Entry[K, V] { - return l.insert(&Entry[K, V]{Value: v, Key: k, ExpiresAt: expiresAt}, at) -} - -// Remove removes e from its list, decrements l.len -func (l *LruList[K, V]) Remove(e *Entry[K, V]) V { - e.prev.next = e.next - e.next.prev = e.prev - e.next = nil // avoid memory leaks - e.prev = nil // avoid memory leaks - e.list = nil - l.len-- - - return e.Value -} - -// move moves e to next to at. -func (l *LruList[K, V]) move(e, at *Entry[K, V]) { - if e == at { - return - } - e.prev.next = e.next - e.next.prev = e.prev - - e.prev = at - e.next = at.next - e.prev.next = e - e.next.prev = e -} - -// PushFront inserts a new element e with value v at the front of list l and returns e. -func (l *LruList[K, V]) PushFront(k K, v V) *Entry[K, V] { - l.lazyInit() - return l.insertValue(k, v, time.Time{}, &l.root) -} - -// PushFrontExpirable inserts a new expirable element e with Value v at the front of list l and returns e. -func (l *LruList[K, V]) PushFrontExpirable(k K, v V, expiresAt time.Time) *Entry[K, V] { - l.lazyInit() - return l.insertValue(k, v, expiresAt, &l.root) -} - -// MoveToFront moves element e to the front of list l. -// If e is not an element of l, the list is not modified. -// The element must not be nil. -func (l *LruList[K, V]) MoveToFront(e *Entry[K, V]) { - if e.list != l || l.root.next == e { - return - } - // see comment in List.Remove about initialization of l - l.move(e, &l.root) -} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/lru.go b/vendor/github.com/hashicorp/golang-lru/v2/lru.go deleted file mode 100644 index a2655f1f3..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/lru.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package lru - -import ( - "sync" - - "github.com/hashicorp/golang-lru/v2/simplelru" -) - -const ( - // DefaultEvictedBufferSize defines the default buffer size to store evicted key/val - DefaultEvictedBufferSize = 16 -) - -// Cache is a thread-safe fixed size LRU cache. -type Cache[K comparable, V any] struct { - lru *simplelru.LRU[K, V] - evictedKeys []K - evictedVals []V - onEvictedCB func(k K, v V) - lock sync.RWMutex -} - -// New creates an LRU of the given size. -func New[K comparable, V any](size int) (*Cache[K, V], error) { - return NewWithEvict[K, V](size, nil) -} - -// NewWithEvict constructs a fixed size cache with the given eviction -// callback. -func NewWithEvict[K comparable, V any](size int, onEvicted func(key K, value V)) (c *Cache[K, V], err error) { - // create a cache with default settings - c = &Cache[K, V]{ - onEvictedCB: onEvicted, - } - if onEvicted != nil { - c.initEvictBuffers() - onEvicted = c.onEvicted - } - c.lru, err = simplelru.NewLRU(size, onEvicted) - return -} - -func (c *Cache[K, V]) initEvictBuffers() { - c.evictedKeys = make([]K, 0, DefaultEvictedBufferSize) - c.evictedVals = make([]V, 0, DefaultEvictedBufferSize) -} - -// onEvicted save evicted key/val and sent in externally registered callback -// outside of critical section -func (c *Cache[K, V]) onEvicted(k K, v V) { - c.evictedKeys = append(c.evictedKeys, k) - c.evictedVals = append(c.evictedVals, v) -} - -// Purge is used to completely clear the cache. -func (c *Cache[K, V]) Purge() { - var ks []K - var vs []V - c.lock.Lock() - c.lru.Purge() - if c.onEvictedCB != nil && len(c.evictedKeys) > 0 { - ks, vs = c.evictedKeys, c.evictedVals - c.initEvictBuffers() - } - c.lock.Unlock() - // invoke callback outside of critical section - if c.onEvictedCB != nil { - for i := 0; i < len(ks); i++ { - c.onEvictedCB(ks[i], vs[i]) - } - } -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *Cache[K, V]) Add(key K, value V) (evicted bool) { - var k K - var v V - c.lock.Lock() - evicted = c.lru.Add(key, value) - if c.onEvictedCB != nil && evicted { - k, v = c.evictedKeys[0], c.evictedVals[0] - c.evictedKeys, c.evictedVals = c.evictedKeys[:0], c.evictedVals[:0] - } - c.lock.Unlock() - if c.onEvictedCB != nil && evicted { - c.onEvictedCB(k, v) - } - return -} - -// Get looks up a key's value from the cache. -func (c *Cache[K, V]) Get(key K) (value V, ok bool) { - c.lock.Lock() - value, ok = c.lru.Get(key) - c.lock.Unlock() - return value, ok -} - -// Contains checks if a key is in the cache, without updating the -// recent-ness or deleting it for being stale. -func (c *Cache[K, V]) Contains(key K) bool { - c.lock.RLock() - containKey := c.lru.Contains(key) - c.lock.RUnlock() - return containKey -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *Cache[K, V]) Peek(key K) (value V, ok bool) { - c.lock.RLock() - value, ok = c.lru.Peek(key) - c.lock.RUnlock() - return value, ok -} - -// ContainsOrAdd checks if a key is in the cache without updating the -// recent-ness or deleting it for being stale, and if not, adds the value. -// Returns whether found and whether an eviction occurred. -func (c *Cache[K, V]) ContainsOrAdd(key K, value V) (ok, evicted bool) { - var k K - var v V - c.lock.Lock() - if c.lru.Contains(key) { - c.lock.Unlock() - return true, false - } - evicted = c.lru.Add(key, value) - if c.onEvictedCB != nil && evicted { - k, v = c.evictedKeys[0], c.evictedVals[0] - c.evictedKeys, c.evictedVals = c.evictedKeys[:0], c.evictedVals[:0] - } - c.lock.Unlock() - if c.onEvictedCB != nil && evicted { - c.onEvictedCB(k, v) - } - return false, evicted -} - -// PeekOrAdd checks if a key is in the cache without updating the -// recent-ness or deleting it for being stale, and if not, adds the value. -// Returns whether found and whether an eviction occurred. -func (c *Cache[K, V]) PeekOrAdd(key K, value V) (previous V, ok, evicted bool) { - var k K - var v V - c.lock.Lock() - previous, ok = c.lru.Peek(key) - if ok { - c.lock.Unlock() - return previous, true, false - } - evicted = c.lru.Add(key, value) - if c.onEvictedCB != nil && evicted { - k, v = c.evictedKeys[0], c.evictedVals[0] - c.evictedKeys, c.evictedVals = c.evictedKeys[:0], c.evictedVals[:0] - } - c.lock.Unlock() - if c.onEvictedCB != nil && evicted { - c.onEvictedCB(k, v) - } - return -} - -// Remove removes the provided key from the cache. -func (c *Cache[K, V]) Remove(key K) (present bool) { - var k K - var v V - c.lock.Lock() - present = c.lru.Remove(key) - if c.onEvictedCB != nil && present { - k, v = c.evictedKeys[0], c.evictedVals[0] - c.evictedKeys, c.evictedVals = c.evictedKeys[:0], c.evictedVals[:0] - } - c.lock.Unlock() - if c.onEvictedCB != nil && present { - c.onEvictedCB(k, v) - } - return -} - -// Resize changes the cache size. -func (c *Cache[K, V]) Resize(size int) (evicted int) { - var ks []K - var vs []V - c.lock.Lock() - evicted = c.lru.Resize(size) - if c.onEvictedCB != nil && evicted > 0 { - ks, vs = c.evictedKeys, c.evictedVals - c.initEvictBuffers() - } - c.lock.Unlock() - if c.onEvictedCB != nil && evicted > 0 { - for i := 0; i < len(ks); i++ { - c.onEvictedCB(ks[i], vs[i]) - } - } - return evicted -} - -// RemoveOldest removes the oldest item from the cache. -func (c *Cache[K, V]) RemoveOldest() (key K, value V, ok bool) { - var k K - var v V - c.lock.Lock() - key, value, ok = c.lru.RemoveOldest() - if c.onEvictedCB != nil && ok { - k, v = c.evictedKeys[0], c.evictedVals[0] - c.evictedKeys, c.evictedVals = c.evictedKeys[:0], c.evictedVals[:0] - } - c.lock.Unlock() - if c.onEvictedCB != nil && ok { - c.onEvictedCB(k, v) - } - return -} - -// GetOldest returns the oldest entry -func (c *Cache[K, V]) GetOldest() (key K, value V, ok bool) { - c.lock.RLock() - key, value, ok = c.lru.GetOldest() - c.lock.RUnlock() - return -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *Cache[K, V]) Keys() []K { - c.lock.RLock() - keys := c.lru.Keys() - c.lock.RUnlock() - return keys -} - -// Values returns a slice of the values in the cache, from oldest to newest. -func (c *Cache[K, V]) Values() []V { - c.lock.RLock() - values := c.lru.Values() - c.lock.RUnlock() - return values -} - -// Len returns the number of items in the cache. -func (c *Cache[K, V]) Len() int { - c.lock.RLock() - length := c.lru.Len() - c.lock.RUnlock() - return length -} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/LICENSE_list b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/LICENSE_list deleted file mode 100644 index c4764e6b2..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/LICENSE_list +++ /dev/null @@ -1,29 +0,0 @@ -This license applies to simplelru/list.go - -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go deleted file mode 100644 index f69792388..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package simplelru - -import ( - "errors" - - "github.com/hashicorp/golang-lru/v2/internal" -) - -// EvictCallback is used to get a callback when a cache entry is evicted -type EvictCallback[K comparable, V any] func(key K, value V) - -// LRU implements a non-thread safe fixed size LRU cache -type LRU[K comparable, V any] struct { - size int - evictList *internal.LruList[K, V] - items map[K]*internal.Entry[K, V] - onEvict EvictCallback[K, V] -} - -// NewLRU constructs an LRU of the given size -func NewLRU[K comparable, V any](size int, onEvict EvictCallback[K, V]) (*LRU[K, V], error) { - if size <= 0 { - return nil, errors.New("must provide a positive size") - } - - c := &LRU[K, V]{ - size: size, - evictList: internal.NewList[K, V](), - items: make(map[K]*internal.Entry[K, V]), - onEvict: onEvict, - } - return c, nil -} - -// Purge is used to completely clear the cache. -func (c *LRU[K, V]) Purge() { - for k, v := range c.items { - if c.onEvict != nil { - c.onEvict(k, v.Value) - } - delete(c.items, k) - } - c.evictList.Init() -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *LRU[K, V]) Add(key K, value V) (evicted bool) { - // Check for existing item - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - ent.Value = value - return false - } - - // Add new item - ent := c.evictList.PushFront(key, value) - c.items[key] = ent - - evict := c.evictList.Length() > c.size - // Verify size not exceeded - if evict { - c.removeOldest() - } - return evict -} - -// Get looks up a key's value from the cache. -func (c *LRU[K, V]) Get(key K) (value V, ok bool) { - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - return ent.Value, true - } - return -} - -// Contains checks if a key is in the cache, without updating the recent-ness -// or deleting it for being stale. -func (c *LRU[K, V]) Contains(key K) (ok bool) { - _, ok = c.items[key] - return ok -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *LRU[K, V]) Peek(key K) (value V, ok bool) { - var ent *internal.Entry[K, V] - if ent, ok = c.items[key]; ok { - return ent.Value, true - } - return -} - -// Remove removes the provided key from the cache, returning if the -// key was contained. -func (c *LRU[K, V]) Remove(key K) (present bool) { - if ent, ok := c.items[key]; ok { - c.removeElement(ent) - return true - } - return false -} - -// RemoveOldest removes the oldest item from the cache. -func (c *LRU[K, V]) RemoveOldest() (key K, value V, ok bool) { - if ent := c.evictList.Back(); ent != nil { - c.removeElement(ent) - return ent.Key, ent.Value, true - } - return -} - -// GetOldest returns the oldest entry -func (c *LRU[K, V]) GetOldest() (key K, value V, ok bool) { - if ent := c.evictList.Back(); ent != nil { - return ent.Key, ent.Value, true - } - return -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *LRU[K, V]) Keys() []K { - keys := make([]K, c.evictList.Length()) - i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() { - keys[i] = ent.Key - i++ - } - return keys -} - -// Values returns a slice of the values in the cache, from oldest to newest. -func (c *LRU[K, V]) Values() []V { - values := make([]V, len(c.items)) - i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() { - values[i] = ent.Value - i++ - } - return values -} - -// Len returns the number of items in the cache. -func (c *LRU[K, V]) Len() int { - return c.evictList.Length() -} - -// Resize changes the cache size. -func (c *LRU[K, V]) Resize(size int) (evicted int) { - diff := c.Len() - size - if diff < 0 { - diff = 0 - } - for i := 0; i < diff; i++ { - c.removeOldest() - } - c.size = size - return diff -} - -// removeOldest removes the oldest item from the cache. -func (c *LRU[K, V]) removeOldest() { - if ent := c.evictList.Back(); ent != nil { - c.removeElement(ent) - } -} - -// removeElement is used to remove a given list element from the cache -func (c *LRU[K, V]) removeElement(e *internal.Entry[K, V]) { - c.evictList.Remove(e) - delete(c.items, e.Key) - if c.onEvict != nil { - c.onEvict(e.Key, e.Value) - } -} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go deleted file mode 100644 index 043b8bcc3..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -// Package simplelru provides simple LRU implementation based on build-in container/list. -package simplelru - -// LRUCache is the interface for simple LRU cache. -type LRUCache[K comparable, V any] interface { - // Adds a value to the cache, returns true if an eviction occurred and - // updates the "recently used"-ness of the key. - Add(key K, value V) bool - - // Returns key's value from the cache and - // updates the "recently used"-ness of the key. #value, isFound - Get(key K) (value V, ok bool) - - // Checks if a key exists in cache without updating the recent-ness. - Contains(key K) (ok bool) - - // Returns key's value without updating the "recently used"-ness of the key. - Peek(key K) (value V, ok bool) - - // Removes a key from the cache. - Remove(key K) bool - - // Removes the oldest entry from cache. - RemoveOldest() (K, V, bool) - - // Returns the oldest entry from the cache. #key, value, isFound - GetOldest() (K, V, bool) - - // Returns a slice of the keys in the cache, from oldest to newest. - Keys() []K - - // Values returns a slice of the values in the cache, from oldest to newest. - Values() []V - - // Returns the number of items in the cache. - Len() int - - // Clears all cache entries. - Purge() - - // Resizes cache, returning number evicted - Resize(int) int -} diff --git a/vendor/modernc.org/gc/v3/GO-LICENSE b/vendor/modernc.org/gc/v3/GO-LICENSE deleted file mode 100644 index 6a66aea5e..000000000 --- a/vendor/modernc.org/gc/v3/GO-LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/modernc.org/gc/v3/LICENSE b/vendor/modernc.org/gc/v3/LICENSE deleted file mode 100644 index 4bc6276f6..000000000 --- a/vendor/modernc.org/gc/v3/LICENSE +++ /dev/null @@ -1,69 +0,0 @@ -------------------------------------------------------------------------------- -Copyright (c) 2016 The GC Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the names of the authors nor the names of the -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- - -Code in this repository contains or may contain - - - copied original code from - - code based on original code from - - code inspired by original code in - - "The Go Programming Language" project at https://go.googlesource.com/go/. - -Copy of the license of the original code follows below - -------------------------------------------------------------------------------- -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- diff --git a/vendor/modernc.org/gc/v3/Makefile b/vendor/modernc.org/gc/v3/Makefile deleted file mode 100644 index 6d7abd62d..000000000 --- a/vendor/modernc.org/gc/v3/Makefile +++ /dev/null @@ -1,113 +0,0 @@ -.PHONY: all clean edit editor test test2 back report report2 parser2 benchmarks benchmarks2 mem memgo race nreport build_all_targets - -all: - -build_all_targets: - GOOS=darwin GOARCH=amd64 go test -c -o /dev/null - GOOS=darwin GOARCH=arm64 go test -c -o /dev/null - GOOS=freebsd GOARCH=386 go test -c -o /dev/null - GOOS=freebsd GOARCH=amd64 go test -c -o /dev/null - GOOS=freebsd GOARCH=arm go test -c -o /dev/null - GOOS=freebsd GOARCH=arm64 go test -c -o /dev/null - GOOS=illumos GOARCH=amd64 go test -c -o /dev/null - GOOS=linux GOARCH=386 go test -c -o /dev/null - GOOS=linux GOARCH=amd64 go test -c -o /dev/null - GOOS=linux GOARCH=arm go test -c -o /dev/null - GOOS=linux GOARCH=arm64 go test -c -o /dev/null - GOOS=linux GOARCH=ppc64le go test -c -o /dev/null - GOOS=linux GOARCH=riscv64 go test -c -o /dev/null - GOOS=linux GOARCH=s390x go test -c -o /dev/null - GOOS=netbsd GOARCH=386 go test -c -o /dev/null - GOOS=netbsd GOARCH=amd64 go test -c -o /dev/null - GOOS=netbsd GOARCH=arm go test -c -o /dev/null - GOOS=openbsd GOARCH=386 go test -c -o /dev/null - GOOS=openbsd GOARCH=amd64 go test -c -o /dev/null - GOOS=openbsd GOARCH=arm64 go test -c -o /dev/null - GOOS=windows GOARCH=386 go test -c -o /dev/null - GOOS=windows GOARCH=amd64 go test -c -o /dev/null - GOOS=windows GOARCH=arm64 go test -c -o /dev/null - -clean: - rm -f cpu.test mem.test *.out - go clean - -edit: - @touch log - @if [ -f "Session.vim" ]; then gvim -S & else gvim -p Makefile all_test.go gc.go & fi - -editor: - gofmt -l -s -w *.go - go test -c -o /dev/null 2>&1 | tee log-editor - -race: - go test -v -failfast -heap -race 2>&1 | tee log-test - @git diff testdata/ || true - @git status - @grep TOTAL log-test || true - grep 'FAIL\|TODO' log-test || true - -test: - go test -v -failfast -trctodo -exterr -heap 2>&1 | tee log-test - @git diff testdata/ || true - @git status - @grep TOTAL log-test || true - grep 'FAIL\|TODO' log-test || true - -test2: - go test -v -failfast -trctodo -exterr -src $$HOME/src 2>&1 | tee log-test2 - @git diff testdata/ || true - @git status - @grep TOTAL log-test2 || true - grep 'FAIL\|TODO' log-test2 || true - -parser2: - go test -v -failfast -run TestParser -src $$HOME/src 2>&1 | tee log-parser2 - @git diff testdata/ || true - @git status - @grep TOTAL log-parser2 || true - grep 'FAIL\|TODO' log-parser2 || true - -back: - go test -v -failfast -noback 2>&1 | tee log-back - @git diff testdata/ || true - @git status - @grep TOTAL log-back || true - grep 'FAIL\|TODO' log-back || true - -nreport: - touch log-nreport - cp log-nreport log-nreport0 - go test -v -failfast -run TestParser -heap -nreport 2>&1 | tee log-nreport - @git diff testdata/ || true - @git status - @grep TOTAL log-report || true - grep 'FAIL\|TODO' log-report || true - -report: - go test -v -failfast -run TestParser -report 2>&1 | tee log-report - @git diff testdata/ || true - @git status - @grep TOTAL log-report || true - grep 'FAIL\|TODO' log-report || true - -report2: - go test -v -failfast -run TestParser -src $$HOME/src -report 2>&1 | tee log-report2 - @git diff testdata/ || true - @git status - @grep TOTAL log-report2 || true - grep 'FAIL\|TODO' log-report2 || true - - -benchmarks: - go test -v -run @ -bench . 2>&1 | tee log-benchmarks - -benchmarks2: - go test -v -run @ -bench . -bsrc $$HOME/src 2>&1 | tee log-benchmarks2 - -mem: - go test -run @ -bench BenchmarkParser -memprofile mem.out - go tool pprof --lines --alloc_space *.test mem.out - -memgo: - go test -run @ -bench BenchmarkGoParser -memprofile mem.out - go tool pprof --lines --alloc_space *.test mem.out diff --git a/vendor/modernc.org/gc/v3/abi.go b/vendor/modernc.org/gc/v3/abi.go deleted file mode 100644 index 2f0964ac5..000000000 --- a/vendor/modernc.org/gc/v3/abi.go +++ /dev/null @@ -1,682 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // import "modernc.org/gc/v3" - -import ( - "encoding/binary" - "fmt" -) - -var ( - byteOrders = map[string]binary.ByteOrder{ - "386": binary.LittleEndian, - "amd64": binary.LittleEndian, - "arm": binary.LittleEndian, - "arm64": binary.LittleEndian, - "ppc64le": binary.LittleEndian, - "riscv64": binary.LittleEndian, - "s390x": binary.BigEndian, - } - - abiTypes = map[[2]string]map[Kind]ABIType{ - // go1.19.1 - {"freebsd", "386"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19.1 - {"freebsd", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.18.5 - {"freebsd", "arm"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19 - {"freebsd", "arm64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"darwin", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"darwin", "arm64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"linux", "386"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19.1 - {"linux", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"linux", "arm"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19.1 - {"linux", "arm64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"linux", "s390x"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"linux", "ppc64le"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"linux", "riscv64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.18.3 - {"netbsd", "386"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.18.3 - {"netbsd", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.18.3 - {"netbsd", "arm"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19 - {"openbsd", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19 - {"openbsd", "arm64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19 - {"openbsd", "386"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19.1 - {"windows", "386"}: { - Bool: {1, 1, 1}, - Chan: {4, 4, 4}, - Complex128: {16, 4, 4}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 4, 4}, - Function: {4, 4, 4}, - Int: {4, 4, 4}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 4, 4}, - Int8: {1, 1, 1}, - Interface: {8, 4, 4}, - Map: {4, 4, 4}, - Pointer: {4, 4, 4}, - Slice: {12, 4, 4}, - String: {8, 4, 4}, - Uint: {4, 4, 4}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 4, 4}, - Uint8: {1, 1, 1}, - Uintptr: {4, 4, 4}, - UnsafePointer: {4, 4, 4}, - }, - // go1.19.1 - {"windows", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.1 - {"windows", "arm64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - // go1.19.3 - {"illumos", "amd64"}: { - Bool: {1, 1, 1}, - Chan: {8, 8, 8}, - Complex128: {16, 8, 8}, - Complex64: {8, 4, 4}, - Float32: {4, 4, 4}, - Float64: {8, 8, 8}, - Function: {8, 8, 8}, - Int: {8, 8, 8}, - Int16: {2, 2, 2}, - Int32: {4, 4, 4}, - Int64: {8, 8, 8}, - Int8: {1, 1, 1}, - Interface: {16, 8, 8}, - Map: {8, 8, 8}, - Pointer: {8, 8, 8}, - Slice: {24, 8, 8}, - String: {16, 8, 8}, - Uint: {8, 8, 8}, - Uint16: {2, 2, 2}, - Uint32: {4, 4, 4}, - Uint64: {8, 8, 8}, - Uint8: {1, 1, 1}, - Uintptr: {8, 8, 8}, - UnsafePointer: {8, 8, 8}, - }, - } -) - -// ABI describes selected parts of the Application Binary Interface. -type ABI struct { - ByteOrder binary.ByteOrder - goarch string - goos string - Types map[Kind]ABIType -} - -type ABIType struct { - Size int64 - Align int64 - FieldAlign int64 -} - -// NewABI creates an ABI based on the os+arch pair. -func NewABI(os, arch string) (*ABI, error) { - byteOrder, ok := byteOrders[arch] - if !ok { - return nil, fmt.Errorf("unsupported arch: %s", arch) - } - - types0, ok := abiTypes[[2]string{os, arch}] - if !ok { - return nil, fmt.Errorf("unsupported os/arch: %s/%s", os, arch) - } - - types := make(map[Kind]ABIType, len(types0)) - for k, v := range types0 { - types[k] = v - } - return &ABI{ - ByteOrder: byteOrder, - Types: types, - }, nil -} diff --git a/vendor/modernc.org/gc/v3/check.go b/vendor/modernc.org/gc/v3/check.go deleted file mode 100644 index 0c5e0a260..000000000 --- a/vendor/modernc.org/gc/v3/check.go +++ /dev/null @@ -1,598 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // modernc.org/gc/v3 - -import ( - "fmt" - "go/constant" - "go/token" - "os" - "path/filepath" - "strings" - "sync" -) - -type ctx struct { - ast *AST - cfg *Config - errs errList - iota int64 - pkg *Package - - int32 Type // Set by newCtx - untypedFloat Type // Set by newCtx - untypedInt Type // Set by newCtx - untypedString Type // Set by newCtx -} - -func newCtx(cfg *Config) (r *ctx) { - r = &ctx{ - cfg: cfg, - iota: -1, // -> Invalid - } - r.int32 = r.newPredeclaredType(znode, Int32) - r.untypedFloat = r.newPredeclaredType(znode, UntypedFloat) - r.untypedInt = r.newPredeclaredType(znode, UntypedInt) - r.untypedString = r.newPredeclaredType(znode, UntypedString) - return r -} - -func (c *ctx) err(n Node, msg string, args ...interface{}) { - var pos token.Position - if n != nil { - pos = n.Position() - } - s := fmt.Sprintf(msg, args...) - if trcTODOs && strings.HasPrefix(s, "TODO") { - fmt.Fprintf(os.Stderr, "%v: %s (%v)\n", pos, s, origin(2)) - os.Stderr.Sync() - } - switch { - case extendedErrors: - c.errs.err(pos, "%s (%v: %v: %v)", s, origin(4), origin(3), origin(2)) - default: - c.errs.err(pos, s) - } -} - -func (c *ctx) isBuiltin() bool { return c.pkg.Scope.kind == UniverseScope } -func (c *ctx) isUnsafe() bool { return c.pkg.isUnsafe } - -func (c *ctx) lookup(sc *Scope, id Token) (pkg *Package, in *Scope, r named) { - sc0 := sc - pkg = c.pkg - for { - switch in, nm := sc.lookup(id); x := nm.n.(type) { - case *TypeDefNode: - if sc.kind == UniverseScope { - if sc0.kind != UniverseScope && token.IsExported(id.Src()) { - // trc("%v: %q %v %v", id.Position(), id.Src(), sc0.kind, sc.kind) - return nil, nil, r - } - } - - return x.pkg, in, nm - default: - panic(todo("%v: %q %T", id.Position(), id.Src(), x)) - } - } -} - -func (n *Package) check(c *ctx) (err error) { - if n == nil { - return nil - } - - c.pkg = n - // trc("PKG %q", n.ImportPath) - // defer func() { trc("PKG %q -> err: %v", n.ImportPath, err) }() - for _, v := range n.GoFiles { - path := filepath.Join(n.FSPath, v.Name()) - n.AST[path].check(c) - } - return c.errs.Err() -} - -func (n *AST) check(c *ctx) { - if n == nil { - return - } - - c.ast = n - n.SourceFile.check(c) -} - -func (n *SourceFileNode) check(c *ctx) { - if n == nil { - return - } - - n.PackageClause.check(c) - for l := n.ImportDeclList; l != nil; l = l.List { - l.ImportDecl.check(c) - } - for l := n.TopLevelDeclList; l != nil; l = l.List { - switch x := l.TopLevelDecl.(type) { - case *TypeDeclNode: - x.check(c) - case *ConstDeclNode: - x.check(c) - case *VarDeclNode: - x.check(c) - case *FunctionDeclNode: - x.check(c) - case *MethodDeclNode: - x.check(c) - default: - panic(todo("%v: %T %s", x.Position(), x, x.Source(false))) - } - } -} - -func (n *MethodDeclNode) check(c *ctx) { - if n == nil { - return - } - - n.Receiver.check(c) - n.Signature.check(c) -} - -func (n *FunctionDeclNode) check(c *ctx) { - if n == nil { - return - } - - if c.isBuiltin() { - switch nm := n.FunctionName.IDENT.Src(); nm { - case - "append", - "cap", - "close", - "complex", - "copy", - "delete", - "imag", - "len", - "make", - "new", - "panic", - "print", - "println", - "real", - "recover", - - // Go 1.21 - "max", - "min", - "clear": - - n.Signature.t = c.newPredeclaredType(n, Function) - default: - panic(todo("%v: %q %s", n.Position(), nm, n.Source(false))) - } - return - } - - n.Signature.check(c) - if n.TypeParameters != nil { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - } -} - -func (n *SignatureNode) check(c *ctx) Type { - if n == nil { - return Invalid - } - - if !n.enter(c, n) { - return n.Type() - } - - in := n.Parameters.check(c) - out := n.Result.check(c) - return n.setType(newTupleType(n.Parameters, []Type{in, out})) -} - -func (n *ResultNode) check(c *ctx) Type { - if n == nil { - return Invalid - } - - switch { - case n.Parameters != nil: - return n.Parameters.check(c) - case n.TypeNode != nil: - return n.TypeNode.check(c) - default: - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - } -} - -func (n *ParametersNode) check(c *ctx) Type { - if n == nil { - return Invalid - } - - r := newTupleType(n, nil) - for l := n.ParameterDeclList; l != nil; l = l.List { - r.Types = append(r.Types, l.ParameterDecl.check(c)...) - } - return r -} - -func (n *ParameterDeclNode) check(c *ctx) (r []Type) { - if n == nil { - return nil - } - - t := n.TypeNode.check(c) - for l := n.IdentifierList; l != nil; l = l.List { - r = append(r, t) - } - return r -} - -func (n *VarDeclNode) check(c *ctx) { - if n == nil { - return - } - - switch x := n.VarSpec.(type) { - case *VarSpecNode: - x.check(c) - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } -} - -func (n *VarSpecNode) check(c *ctx) { - if n == nil { - return - } - - if c.isBuiltin() { - switch nm := n.IDENT.Src(); nm { - case "nil": - n.TypeNode = c.newPredeclaredType(n, UntypedNil) - default: - panic(todo("%v: %q", n.IDENT.Position(), nm)) - } - return - } - - if n.TypeNode != nil { - c.err(n, "TODO %v", n.TypeNode.Source(false)) - } - var e []Expression - for l := n.ExpressionList; l != nil; l = l.List { - e = append(e, l.Expression.checkExpr(c)) - } - switch len(e) { - default: - panic(todo("", len(e))) - c.err(n, "TODO %v", len(e)) - } -} - -func (n *ConstDeclNode) check(c *ctx) { - if n == nil { - return - } - - switch x := n.ConstSpec.(type) { - case *ConstSpecListNode: - var prev Node - for l := x; l != nil; l = l.List { - switch y := l.ConstSpec.(type) { - case *ConstSpecNode: - y.check(c, prev) - if y.Expression != nil || y.TypeNode != nil { - prev = y - } - default: - panic(todo("%v: %T %s", n.Position(), y, n.Source(false))) - } - } - case *ConstSpecNode: - x.check(c, nil) - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - -} - -func (n *ConstSpecNode) check(c *ctx, prev Node) { - if n == nil { - return - } - - if !n.enter(c, n) { - if n.guard == guardChecking { - panic(todo("")) // report recursive - } - return - } - - defer func() { n.guard = guardChecked }() - - if c.isBuiltin() { - switch n.IDENT.Src() { - case "true": - switch x := n.Expression.(type) { - case *BinaryExpressionNode: - x.setValue(trueVal) - x.setType(c.newPredeclaredType(x, UntypedBool)) - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - case "false": - switch x := n.Expression.(type) { - case *BinaryExpressionNode: - x.setValue(falseVal) - x.setType(c.newPredeclaredType(x, UntypedBool)) - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - case "iota": - switch x := n.Expression.(type) { - case *BasicLitNode: - // ok - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - default: - panic(todo("", n.Position(), n.Source(false))) - } - return - } - - save := c.iota - c.iota = n.iota - - defer func() { c.iota = save }() - - switch { - case n.Expression != nil: - n.Expression = n.Expression.checkExpr(c) - if n.TypeNode == nil { - n.TypeNode = n.Expression.Type() - return - } - - t := n.TypeNode.check(c) - trc("", t) - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - default: - // var e Expression - // var pe *Expression - // switch { - // case n.Expression != nil: - // e = n.Expression - // pe = &n.Expression - // default: - // switch x := prev.(type) { - // case *ConstSpecNode: - // e = x.Expression.clone() - // pe = &e - // default: - // panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - // } - // } - // ev, et := e.checkExpr(c, pe) - // e = *pe - // if ev.Kind() == constant.Unknown { - // c.err(e, "%s is not a constant", e.Source(false)) - // n.t = Invalid - // n.setValue(unknown) - // return Invalid - // } - // switch { - // case n.t == nil: - // n.t = et - // default: - - // c.err(n.Expression, "cannot assign %v (type %v) to type %v", ev, et, n.Type()) - // return Invalid - // } else { - // n.setValue(convertValue(c, e, ev, n.Type())) - // } - // } - // return n.Type() - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - } - -} - -func (n *TypeDeclNode) check(c *ctx) { - if n == nil { - return - } - - for l := n.TypeSpecList; l != nil; l = l.List { - switch x := l.TypeSpec.(type) { - case *TypeDefNode: - switch { - case c.isBuiltin(): - x.pkg = c.pkg - switch nm := x.IDENT.Src(); nm { - case "bool": - x.TypeNode = c.newPredeclaredType(x, Bool) - case "int": - x.TypeNode = c.newPredeclaredType(x, Int) - c.cfg.int = x.TypeNode - case "int8": - x.TypeNode = c.newPredeclaredType(x, Int8) - case "int16": - x.TypeNode = c.newPredeclaredType(x, Int16) - case "int32": - x.TypeNode = c.newPredeclaredType(x, Int32) - case "int64": - x.TypeNode = c.newPredeclaredType(x, Int64) - case "uint": - x.TypeNode = c.newPredeclaredType(x, Uint) - c.cfg.uint = x.TypeNode - case "uint8": - x.TypeNode = c.newPredeclaredType(x, Uint8) - case "uint16": - x.TypeNode = c.newPredeclaredType(x, Uint16) - case "uint32": - x.TypeNode = c.newPredeclaredType(x, Uint32) - case "uint64": - x.TypeNode = c.newPredeclaredType(x, Uint64) - case "uintptr": - x.TypeNode = c.newPredeclaredType(x, Uintptr) - case "string": - x.TypeNode = c.newPredeclaredType(x, String) - case "float32": - x.TypeNode = c.newPredeclaredType(x, Float32) - case "float64": - x.TypeNode = c.newPredeclaredType(x, Float64) - case "complex64": - x.TypeNode = c.newPredeclaredType(x, Complex64) - case "complex128": - x.TypeNode = c.newPredeclaredType(x, Complex128) - case "comparable": - x.TypeNode = c.newPredeclaredType(x, Interface) - case "error": - x.check(c) - default: - if token.IsExported(nm) { - delete(c.pkg.Scope.nodes, nm) - return - } - - panic(todo("%v: %T %s", x.Position(), x, x.Source(false))) - } - case c.isUnsafe(): - switch nm := x.IDENT.Src(); nm { - case "ArbitraryType", "IntegerType", "Pointer": - x.TypeNode.check(c) - default: - panic(todo("%v: %T %s", x.Position(), x, x.Source(false))) - } - default: - switch { - case x.TypeParameters != nil: - panic(todo("%v: %T %s", x.Position(), x, x.Source(false))) - default: - x.check(c) - } - } - case *AliasDeclNode: - x.check(c) - default: - panic(todo("%v: %T %s", x.Position(), x, x.Source(false))) - } - } -} - -func (n *AliasDeclNode) check(c *ctx) { - if n == nil { - return - } - - n.TypeNode.check(c) -} - -func (n *ImportDeclNode) check(c *ctx) { - if n == nil { - return - } - - type result struct { - spec *ImportSpecNode - pkg *Package - err error - } - var a []*result - var wg sync.WaitGroup - for l := n.ImportSpecList; l != nil; l = l.List { - r := &result{} - a = append(a, r) - wg.Add(1) - go func(isln *ImportSpecListNode, r *result) { - - defer wg.Done() - - r.spec = isln.ImportSpec - r.pkg, r.err = r.spec.check(c) - r.spec.pkg = r.pkg - }(l, r) - } - wg.Wait() - fileScope := c.ast.FileScope - pkgScope := c.pkg.Scope - for _, v := range a { - switch x := v.err.(type) { - case nil: - // ok - default: - panic(todo("%v: %T: %s", v.spec.Position(), x, x)) - } - if c.pkg.ImportPath == "builtin" && v.spec.ImportPath.Src() == `"cmp"` { - continue - } - - switch ex := fileScope.declare(v.pkg.Name, v.spec, 0, nil, true); { - case ex.declTok.IsValid(): - c.err(n, "%s redeclared, previous declaration at %v:", v.pkg.Name.Src(), ex.declTok.Position()) - continue - } - - switch ex := pkgScope.declare(v.pkg.Name, v.spec, 0, nil, true); { - case ex.declTok.IsValid(): - c.err(n, "%s redeclared, previous declaration at %v:", v.pkg.Name.Src(), ex.declTok.Position()) - continue - } - } -} - -func (n *ImportSpecNode) check(c *ctx) (*Package, error) { - if n == nil { - return nil, nil - } - - switch { - case n.PERIOD.IsValid(): - panic(todo("", n.Position(), n.Source(false))) - case n.PackageName.IsValid(): - //TODO version - check := c.pkg.typeCheck - switch check { - case TypeCheckAll: - // nop - default: - panic(todo("", check)) - } - return c.cfg.newPackage(c.pkg.FSPath, constant.StringVal(n.ImportPath.Value()), "", nil, false, check, c.pkg.guard) - default: - //TODO version - check := c.pkg.typeCheck - switch check { - case TypeCheckAll: - // nop - default: - if c.pkg.ImportPath == "builtin" && n.ImportPath.Src() == `"cmp"` { - return nil, nil - } - } - return c.cfg.newPackage(c.pkg.FSPath, constant.StringVal(n.ImportPath.Value()), "", nil, false, check, c.pkg.guard) - } -} - -func (n *PackageClauseNode) check(c *ctx) { - if n == nil { - return - } - - nm := n.PackageName.Src() - if ex := c.pkg.Name; ex.IsValid() && ex.Src() != nm { - c.err(n.PackageName, "found different packages %q and %q", ex.Src(), nm) - return - } - - c.pkg.Name = n.PackageName -} diff --git a/vendor/modernc.org/gc/v3/etc.go b/vendor/modernc.org/gc/v3/etc.go deleted file mode 100644 index fe8d8fbf6..000000000 --- a/vendor/modernc.org/gc/v3/etc.go +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // modernc.org/gc/v3 - -import ( - "fmt" - "go/token" - "math" - "os" - "path/filepath" - "runtime" - "sort" - "strconv" - "strings" - "sync" - - "github.com/dustin/go-humanize" -) - -// The list of tokens. -const ( - // Special tokens - ILLEGAL = token.ILLEGAL - EOF = token.EOF - COMMENT = token.COMMENT - - // Identifiers and basic type literals - // (these tokens stand for classes of literals) - IDENT = token.IDENT // main - INT = token.INT // 12345 - FLOAT = token.FLOAT // 123.45 - IMAG = token.IMAG // 123.45i - CHAR = token.CHAR // 'a' - STRING = token.STRING // "abc" - - // Operators and delimiters - ADD = token.ADD // + - SUB = token.SUB // - - MUL = token.MUL // * - QUO = token.QUO // / - REM = token.REM // % - - AND = token.AND // & - OR = token.OR // | - XOR = token.XOR // ^ - SHL = token.SHL // << - SHR = token.SHR // >> - AND_NOT = token.AND_NOT // &^ - - ADD_ASSIGN = token.ADD_ASSIGN // += - SUB_ASSIGN = token.SUB_ASSIGN // -= - MUL_ASSIGN = token.MUL_ASSIGN // *= - QUO_ASSIGN = token.QUO_ASSIGN // /= - REM_ASSIGN = token.REM_ASSIGN // %= - - AND_ASSIGN = token.AND_ASSIGN // &= - OR_ASSIGN = token.OR_ASSIGN // |= - XOR_ASSIGN = token.XOR_ASSIGN // ^= - SHL_ASSIGN = token.SHL_ASSIGN // <<= - SHR_ASSIGN = token.SHR_ASSIGN // >>= - AND_NOT_ASSIGN = token.AND_NOT_ASSIGN // &^= - - LAND = token.LAND // && - LOR = token.LOR // || - ARROW = token.ARROW // <- - INC = token.INC // ++ - DEC = token.DEC // -- - - EQL = token.EQL // == - LSS = token.LSS // < - GTR = token.GTR // > - ASSIGN = token.ASSIGN // = - NOT = token.NOT // ! - - NEQ = token.NEQ // != - LEQ = token.LEQ // <= - GEQ = token.GEQ // >= - DEFINE = token.DEFINE // := - ELLIPSIS = token.ELLIPSIS // ... - - LPAREN = token.LPAREN // ( - LBRACK = token.LBRACK // [ - LBRACE = token.LBRACE // { - COMMA = token.COMMA // , - PERIOD = token.PERIOD // . - - RPAREN = token.RPAREN // ) - RBRACK = token.RBRACK // ] - RBRACE = token.RBRACE // } - SEMICOLON = token.SEMICOLON // ; - COLON = token.COLON // : - - // Keywords - BREAK = token.BREAK - CASE = token.CASE - CHAN = token.CHAN - CONST = token.CONST - CONTINUE = token.CONTINUE - - DEFAULT = token.DEFAULT - DEFER = token.DEFER - ELSE = token.ELSE - FALLTHROUGH = token.FALLTHROUGH - FOR = token.FOR - - FUNC = token.FUNC - GO = token.GO - GOTO = token.GOTO - IF = token.IF - IMPORT = token.IMPORT - - INTERFACE = token.INTERFACE - MAP = token.MAP - PACKAGE = token.PACKAGE - RANGE = token.RANGE - RETURN = token.RETURN - - SELECT = token.SELECT - STRUCT = token.STRUCT - SWITCH = token.SWITCH - TYPE = token.TYPE - VAR = token.VAR - - // additional tokens, handled in an ad-hoc manner - TILDE = token.TILDE -) - -var ( - trcTODOs bool - extendedErrors bool -) - -// origin returns caller's short position, skipping skip frames. -func origin(skip int) string { - pc, fn, fl, _ := runtime.Caller(skip) - f := runtime.FuncForPC(pc) - var fns string - if f != nil { - fns = f.Name() - if x := strings.LastIndex(fns, "."); x > 0 { - fns = fns[x+1:] - } - if strings.HasPrefix(fns, "func") { - num := true - for _, c := range fns[len("func"):] { - if c < '0' || c > '9' { - num = false - break - } - } - if num { - return origin(skip + 2) - } - } - } - return fmt.Sprintf("%s:%d:%s", filepath.Base(fn), fl, fns) -} - -// todo prints and returns caller's position and an optional message tagged with TODO. Output goes to stderr. -// -//lint:ignore U1000 whatever -func todo(s string, args ...interface{}) string { - switch { - case s == "": - s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...) - default: - s = fmt.Sprintf(s, args...) - } - r := fmt.Sprintf("%s\n\tTODO (%s)", origin(2), s) - // fmt.Fprintf(os.Stderr, "%s\n", r) - // os.Stdout.Sync() - return r -} - -// trc prints and returns caller's position and an optional message tagged with TRC. Output goes to stderr. -// -//lint:ignore U1000 whatever -func trc(s string, args ...interface{}) string { - switch { - case s == "": - s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...) - default: - s = fmt.Sprintf(s, args...) - } - r := fmt.Sprintf("%s: TRC (%s)", origin(2), s) - fmt.Fprintf(os.Stderr, "%s\n", r) - os.Stderr.Sync() - return r -} - -func extractPos(s string) (p token.Position, ok bool) { - var prefix string - if len(s) > 1 && s[1] == ':' { // c:\foo - prefix = s[:2] - s = s[2:] - } - // "testdata/parser/bug/001.c:1193: ..." - a := strings.Split(s, ":") - // ["testdata/parser/bug/001.c" "1193" "..."] - if len(a) < 2 { - return p, false - } - - line, err := strconv.Atoi(a[1]) - if err != nil { - return p, false - } - - col, err := strconv.Atoi(a[2]) - if err != nil { - col = 1 - } - - return token.Position{Filename: prefix + a[0], Line: line, Column: col}, true -} - -// errorf constructs an error value. If extendedErrors is true, the error will -// contain its origin. -func errorf(s string, args ...interface{}) error { - switch { - case s == "": - s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...) - default: - s = fmt.Sprintf(s, args...) - } - if trcTODOs && strings.HasPrefix(s, "TODO") { - fmt.Fprintf(os.Stderr, "%s (%v)\n", s, origin(2)) - os.Stderr.Sync() - } - switch { - case extendedErrors: - return fmt.Errorf("%s (%v: %v: %v)", s, origin(4), origin(3), origin(2)) - default: - return fmt.Errorf("%s", s) - } -} - -func tokSource(t token.Token) string { - switch t { - case ILLEGAL: - return "ILLEGAL" - case EOF: - return "EOF" - case COMMENT: - return "COMMENT" - case IDENT: - return "IDENT" - case INT: - return "INT" - case FLOAT: - return "FLOAT" - case IMAG: - return "IMAG" - case CHAR: - return "CHAR" - case STRING: - return "STRING" - case ADD: - return "ADD" - case SUB: - return "SUB" - case MUL: - return "MUL" - case QUO: - return "QUO" - case REM: - return "REM" - case AND: - return "AND" - case OR: - return "OR" - case XOR: - return "XOR" - case SHL: - return "SHL" - case SHR: - return "SHR" - case AND_NOT: - return "AND_NOT" - case ADD_ASSIGN: - return "ADD_ASSIGN" - case SUB_ASSIGN: - return "SUB_ASSIGN" - case MUL_ASSIGN: - return "MUL_ASSIGN" - case QUO_ASSIGN: - return "QUO_ASSIGN" - case REM_ASSIGN: - return "REM_ASSIGN" - case AND_ASSIGN: - return "AND_ASSIGN" - case OR_ASSIGN: - return "OR_ASSIGN" - case XOR_ASSIGN: - return "XOR_ASSIGN" - case SHL_ASSIGN: - return "SHL_ASSIGN" - case SHR_ASSIGN: - return "SHR_ASSIGN" - case AND_NOT_ASSIGN: - return "AND_NOT_ASSIGN" - case LAND: - return "LAND" - case LOR: - return "LOR" - case ARROW: - return "ARROW" - case INC: - return "INC" - case DEC: - return "DEC" - case EQL: - return "EQL" - case LSS: - return "LSS" - case GTR: - return "GTR" - case ASSIGN: - return "ASSIGN" - case NOT: - return "NOT" - case NEQ: - return "NEQ" - case LEQ: - return "LEQ" - case GEQ: - return "GEQ" - case DEFINE: - return "DEFINE" - case ELLIPSIS: - return "ELLIPSIS" - case LPAREN: - return "LPAREN" - case LBRACK: - return "LBRACK" - case LBRACE: - return "LBRACE" - case COMMA: - return "COMMA" - case PERIOD: - return "PERIOD" - case RPAREN: - return "RPAREN" - case RBRACK: - return "RBRACK" - case RBRACE: - return "RBRACE" - case SEMICOLON: - return "SEMICOLON" - case COLON: - return "COLON" - case BREAK: - return "BREAK" - case CASE: - return "CASE" - case CHAN: - return "CHAN" - case CONST: - return "CONST" - case CONTINUE: - return "CONTINUE" - case DEFAULT: - return "DEFAULT" - case DEFER: - return "DEFER" - case ELSE: - return "ELSE" - case FALLTHROUGH: - return "FALLTHROUGH" - case FOR: - return "FOR" - case FUNC: - return "FUNC" - case GO: - return "GO" - case GOTO: - return "GOTO" - case IF: - return "IF" - case IMPORT: - return "IMPORT" - case INTERFACE: - return "INTERFACE" - case MAP: - return "MAP" - case PACKAGE: - return "PACKAGE" - case RANGE: - return "RANGE" - case RETURN: - return "RETURN" - case SELECT: - return "SELECT" - case STRUCT: - return "STRUCT" - case SWITCH: - return "SWITCH" - case TYPE: - return "TYPE" - case VAR: - return "VAR" - case TILDE: - return "TILDE" - default: - panic(todo("", int(t), t)) - } -} - -type data struct { - line int - cases int - cnt int -} - -type analyzer struct { - sync.Mutex - m map[int]*data // line: data -} - -func newAnalyzer() *analyzer { - return &analyzer{m: map[int]*data{}} -} - -func (a *analyzer) record(line, cnt int) { - d := a.m[line] - if d == nil { - d = &data{line: line} - a.m[line] = d - } - d.cases++ - d.cnt += cnt -} - -func (a *analyzer) merge(b *analyzer) { - a.Lock() - defer a.Unlock() - - for k, v := range b.m { - d := a.m[k] - if d == nil { - d = &data{line: k} - a.m[k] = d - } - d.cases += v.cases - d.cnt += v.cnt - } -} - -func (a *analyzer) report() string { - var rows []*data - for _, v := range a.m { - rows = append(rows, v) - } - sort.Slice(rows, func(i, j int) bool { - a := rows[i] - b := rows[j] - if a.cases < b.cases { - return true - } - - if a.cases > b.cases { - return false - } - - // a.cases == b.cases - if a.cnt < b.cnt { - return true - } - - if a.cnt > b.cnt { - return false - } - - // a.cnt == b.cnt - return a.line < b.line - }) - var b strings.Builder - var cases, cnt int - for _, row := range rows { - cases += row.cases - cnt += row.cnt - avg := float64(row.cnt) / float64(row.cases) - fmt.Fprintf(&b, "parser.go:%d:\t%16s %16s %8.1f\n", row.line, h(row.cases), h(row.cnt), avg) - } - avg := float64(cnt) / float64(cases) - fmt.Fprintf(&b, "\t\t%16s %16s %8.1f\n", h(cases), h(cnt), avg) - return b.String() -} - -func h(v interface{}) string { - switch x := v.(type) { - case int: - return humanize.Comma(int64(x)) - case int32: - return humanize.Comma(int64(x)) - case int64: - return humanize.Comma(x) - case uint32: - return humanize.Comma(int64(x)) - case uint64: - if x <= math.MaxInt64 { - return humanize.Comma(int64(x)) - } - - return "-" + humanize.Comma(-int64(x)) - } - return fmt.Sprint(v) -} - -type parallel struct { - limiter chan struct{} -} - -func newParallel() *parallel { - return ¶llel{ - limiter: make(chan struct{}, runtime.GOMAXPROCS(0)), - } -} - -func (p *parallel) throttle(f func()) { - p.limiter <- struct{}{} - - defer func() { - <-p.limiter - }() - - f() -} - -func extraTags(verMajor, verMinor int, goos, goarch string) (r []string) { - // https://github.com/golang/go/commit/eeb7899137cda1c2cd60dab65ff41f627436db5b - // - // In Go 1.17 we added register ABI on AMD64 on Linux/macOS/Windows - // as a GOEXPERIMENT, on by default. In Go 1.18, we commit to always - // enabling register ABI on AMD64. - // - // Now "go build" for AMD64 always have goexperiment.regabi* tags - // set. However, at bootstrapping cmd/dist does not set the tags - // when building go_bootstrap. For this to work, unfortunately, we - // need to hard-code AMD64 to use register ABI in runtime code. - if verMajor == 1 { - switch { - case verMinor == 17: - switch goos { - case "linux", "darwin", "windows": - if goarch == "amd64" { - r = append(r, "goexperiment.regabiargs", "goexperiment.regabiwrappers") - } - } - case verMinor >= 18: - if goarch == "amd64" { - r = append(r, "goexperiment.regabiargs", "goexperiment.regabiwrappers") - } - } - } - return r -} diff --git a/vendor/modernc.org/gc/v3/gc.go b/vendor/modernc.org/gc/v3/gc.go deleted file mode 100644 index 1723bd580..000000000 --- a/vendor/modernc.org/gc/v3/gc.go +++ /dev/null @@ -1,761 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate stringer -output stringer.go -linecomment -type=Kind,ScopeKind,ChanDir,TypeCheck - -package gc // modernc.org/gc/v3 - -import ( - "fmt" - "go/build" - "go/build/constraint" - "go/token" - "io" - "io/fs" - "os" - "path/filepath" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "unicode" - - "github.com/hashicorp/golang-lru/v2" -) - -var ( - trcErrors bool -) - -type FileFilter func(cfg *Config, importPath string, matchedFSPaths []string, withTestFiles bool) (pkgFiles []string, err error) - -type TypeCheck int - -const ( - TypeCheckNone TypeCheck = iota - TypeCheckAll -) - -type cacheKey struct { - buildTagsKey string - cfg *Config - fsPath string - goarch string - goos string - gopathKey string - goroot string - importPath string - typeCheck TypeCheck - - withTestFiles bool -} - -type cacheItem struct { - pkg *Package - ch chan struct{} -} - -func newCacheItem() *cacheItem { return &cacheItem{ch: make(chan struct{})} } - -func (c *cacheItem) set(pkg *Package) { - c.pkg = pkg - close(c.ch) -} - -func (c *cacheItem) wait() *Package { - <-c.ch - return c.pkg -} - -type Cache struct { - sync.Mutex - lru *lru.TwoQueueCache[cacheKey, *cacheItem] -} - -func NewCache(size int) (*Cache, error) { - c, err := lru.New2Q[cacheKey, *cacheItem](size) - if err != nil { - return nil, err - } - - return &Cache{lru: c}, nil -} - -func MustNewCache(size int) *Cache { - c, err := NewCache(size) - if err != nil { - panic(todo("", err)) - } - - return c -} - -type ConfigOption func(*Config) error - -// Config configures NewPackage -// -// Config instances can be shared, they are not mutated once created and -// configured. -type Config struct { - abi *ABI - buildTagMap map[string]bool - buildTags []string - buildTagsKey string // Zero byte separated - builtin *Package - cache *Cache - cmp *Package // Go 1.21 - env map[string]string - fs fs.FS - goarch string - gocompiler string // "gc", "gccgo" - goos string - gopath string - gopathKey string // Zero byte separated - goroot string - goversion string - lookup func(rel, importPath, version string) (fsPath string, err error) - parallel *parallel - searchGoPaths []string - searchGoroot []string - - int Type // Set by NewConfig - uint Type // Set by NewConfig - - arch32bit bool - configured bool -} - -// NewConfig returns a newly created config or an error, if any. -func NewConfig(opts ...ConfigOption) (r *Config, err error) { - r = &Config{ - buildTagMap: map[string]bool{}, - env: map[string]string{}, - parallel: newParallel(), - } - - defer func() { - if r != nil { - r.configured = true - } - }() - - r.lookup = r.DefaultLookup - ctx := build.Default - r.goos = r.getenv("GOOS", ctx.GOOS) - r.goarch = r.getenv("GOARCH", ctx.GOARCH) - r.goroot = r.getenv("GOROOT", ctx.GOROOT) - r.gopath = r.getenv("GOPATH", ctx.GOPATH) - r.buildTags = append(r.buildTags, r.goos, r.goarch) - r.gocompiler = runtime.Compiler - for _, opt := range opts { - if err := opt(r); err != nil { - return nil, err - } - } - if r.abi, err = NewABI(r.goos, r.goarch); err != nil { - return nil, err - } - switch r.goarch { - case "386", "arm": - r.arch32bit = true - } - - // During a particular build, the following build tags are satisfied: - // - // the target operating system, as spelled by runtime.GOOS, set with the GOOS environment variable. - // the target architecture, as spelled by runtime.GOARCH, set with the GOARCH environment variable. - // "unix", if GOOS is a Unix or Unix-like system. - // the compiler being used, either "gc" or "gccgo" - // "cgo", if the cgo command is supported (see CGO_ENABLED in 'go help environment'). - // a term for each Go major release, through the current version: "go1.1" from Go version 1.1 onward, "go1.12" from Go 1.12, and so on. - // any additional tags given by the -tags flag (see 'go help build'). - // There are no separate build tags for beta or minor releases. - if r.goversion == "" { - r.goversion = runtime.Version() - } - if !strings.HasPrefix(r.goversion, "go") || !strings.Contains(r.goversion, ".") { - return nil, fmt.Errorf("cannot parse Go version: %s", r.goversion) - } - - ver := strings.SplitN(r.goversion[len("go"):], ".", 2) - verMajor, err := strconv.Atoi(ver[0]) - if err != nil { - return nil, fmt.Errorf("cannot parse Go version %s: %v", r.goversion, err) - } - - if verMajor != 1 { - return nil, fmt.Errorf("unsupported Go version: %s", r.goversion) - } - - switch x, x2 := strings.IndexByte(ver[1], '.'), strings.Index(ver[1], "rc"); { - case x >= 0: - ver[1] = ver[1][:x] - case x2 >= 0: - ver[1] = ver[1][:x2] - } - verMinor, err := strconv.Atoi(ver[1]) - if err != nil { - return nil, fmt.Errorf("cannot parse Go version %s: %v", r.goversion, err) - } - - for i := 1; i <= verMinor; i++ { - r.buildTags = append(r.buildTags, fmt.Sprintf("go%d.%d", verMajor, i)) - } - r.buildTags = append(r.buildTags, r.gocompiler) - r.buildTags = append(r.buildTags, extraTags(verMajor, verMinor, r.goos, r.goarch)...) - if r.getenv("CGO_ENABLED", "1") == "1" { - r.buildTags = append(r.buildTags, "cgo") - } - for i, v := range r.buildTags { - tag := strings.TrimSpace(v) - r.buildTags[i] = tag - r.buildTagMap[tag] = true - } - sort.Strings(r.buildTags) - r.buildTagsKey = strings.Join(r.buildTags, "\x00") - r.searchGoroot = []string{filepath.Join(r.goroot, "src")} - r.searchGoPaths = filepath.SplitList(r.gopath) - r.gopathKey = strings.Join(r.searchGoPaths, "\x00") - for i, v := range r.searchGoPaths { - r.searchGoPaths[i] = filepath.Join(v, "src") - } - - switch r.cmp, err = r.NewPackage("", "cmp", "", nil, false, TypeCheckNone); { - case err != nil: - r.cmp = nil - default: - //TODO r.cmp.Scope.kind = UniverseScope - } - if r.builtin, err = r.NewPackage("", "builtin", "", nil, false, TypeCheckNone); err != nil { - return nil, err - } - - r.builtin.Scope.kind = UniverseScope - if err := r.builtin.check(newCtx(r)); err != nil { - return nil, err - } - - return r, nil -} - -func (c *Config) universe() *Scope { - if c.builtin != nil { - return c.builtin.Scope - } - - return nil -} - -func (c *Config) stat(name string) (fs.FileInfo, error) { - if c.fs == nil { - return os.Stat(name) - } - - name = filepath.ToSlash(name) - if x, ok := c.fs.(fs.StatFS); ok { - return x.Stat(name) - } - - f, err := c.fs.Open(name) - if err != nil { - return nil, err - } - - defer f.Close() - - return f.Stat() -} - -func (c *Config) open(name string) (fs.File, error) { - if c.fs == nil { - return os.Open(name) - } - - name = filepath.ToSlash(name) - return c.fs.Open(name) -} - -func (c *Config) glob(pattern string) (matches []string, err error) { - if c.fs == nil { - return filepath.Glob(pattern) - } - - pattern = filepath.ToSlash(pattern) - return fs.Glob(c.fs, pattern) -} - -func (c *Config) checkConstraints(pos token.Position, sep string) (r bool) { - if !strings.Contains(sep, "//go:build") && !strings.Contains(sep, "+build") { - return true - } - - // defer func() { trc("", r) }() - - lines := strings.Split(sep, "\n") - var build, plusBuild []string - for i, line := range lines { - if constraint.IsGoBuild(line) && i < len(lines)-1 && lines[i+1] == "" { - build = append(build, line) - } - if constraint.IsPlusBuild(line) { - plusBuild = append(plusBuild, line) - } - } - switch len(build) { - case 0: - // ok - case 1: - expr, err := constraint.Parse(build[0]) - if err != nil { - return true - } - - return expr.Eval(func(tag string) (r bool) { - // defer func() { trc("%q: %v", tag, r) }() - switch tag { - case "unix": - return unixOS[c.goos] - default: - return c.buildTagMap[tag] - } - }) - default: - panic(todo("%v: %q", pos, build)) - } - - for _, line := range plusBuild { - expr, err := constraint.Parse(line) - if err != nil { - return true - } - - if !expr.Eval(func(tag string) (r bool) { - // defer func() { trc("%q: %v", tag, r) }() - switch tag { - case "unix": - return unixOS[c.goos] - default: - return c.buildTagMap[tag] - } - }) { - return false - } - } - return true -} - -// Default lookup translates import paths, possibly relative to rel, to file system paths. -func (c *Config) DefaultLookup(rel, importPath, version string) (fsPath string, err error) { - if importPath == "" { - return "", fmt.Errorf("import path cannot be emtpy") - } - - // Implementation restriction: A compiler may restrict ImportPaths to non-empty - // strings using only characters belonging to Unicode's L, M, N, P, and S - // general categories (the Graphic characters without spaces) and may also - // exclude the characters !"#$%&'()*,:;<=>?[\]^`{|} and the Unicode replacement - // character U+FFFD. - if strings.ContainsAny(importPath, "!\"#$%&'()*,:;<=>?[\\]^`{|}\ufffd") { - return "", fmt.Errorf("invalid import path: %s", importPath) - } - - for _, r := range importPath { - if !unicode.Is(unicode.L, r) && - !unicode.Is(unicode.M, r) && - !unicode.Is(unicode.N, r) && - !unicode.Is(unicode.P, r) && - !unicode.Is(unicode.S, r) { - return "", fmt.Errorf("invalid import path: %s", importPath) - } - } - var search []string - ip0 := importPath - switch slash := strings.IndexByte(importPath, '/'); { - case strings.HasPrefix(importPath, "./"): - if rel != "" { - panic(todo("")) - } - - return "", fmt.Errorf("invalid import path: %s", importPath) - case strings.HasPrefix(importPath, "/"): - return importPath, nil - case slash > 0: - ip0 = importPath[:slash] - default: - ip0 = importPath - } - if ip0 != "" { - switch { - case strings.Contains(ip0, "."): - search = c.searchGoPaths - default: - search = c.searchGoroot - } - } - for _, v := range search { - fsPath = filepath.Join(v, importPath) - dir, err := c.open(fsPath) - if err != nil { - continue - } - - fi, err := dir.Stat() - dir.Close() - if err != nil { - continue - } - - if fi.IsDir() { - return fsPath, nil - } - } - - return "", fmt.Errorf("cannot find package %s, searched %v", importPath, search) -} - -func (c *Config) getenv(nm, deflt string) (r string) { - if r = c.env[nm]; r != "" { - return r - } - - if r = os.Getenv(nm); r != "" { - return r - } - - return deflt -} - -func DefaultFileFilter(cfg *Config, importPath string, matchedFSPaths []string, withTestFiles bool) (pkgFiles []string, err error) { - w := 0 - for _, v := range matchedFSPaths { - base := filepath.Base(v) - base = base[:len(base)-len(filepath.Ext(base))] - const testSuffix = "_test" - if strings.HasSuffix(base, testSuffix) { - if !withTestFiles { - continue - } - - base = base[:len(base)-len(testSuffix)] - } - if x := strings.LastIndexByte(base, '_'); x > 0 { - last := base[x+1:] - base = base[:x] - var prevLast string - if x := strings.LastIndexByte(base, '_'); x > 0 { - prevLast = base[x+1:] - } - if last != "" && prevLast != "" { - // *_GOOS_GOARCH - if knownOS[prevLast] && prevLast != cfg.goos { - continue - } - - if knownArch[last] && last != cfg.goarch { - continue - } - } - - if last != "" { - // *_GOOS or *_GOARCH - if knownOS[last] && last != cfg.goos { - continue - } - - if knownArch[last] && last != cfg.goarch { - continue - } - } - } - - matchedFSPaths[w] = v - w++ - } - return matchedFSPaths[:w], nil -} - -// ConfigBuildTags configures build tags. -func ConfigBuildTags(tags []string) ConfigOption { - return func(cfg *Config) error { - if cfg.configured { - return fmt.Errorf("ConfigBuildTags: Config instance already configured") - } - - cfg.buildTags = append(cfg.buildTags, tags...) - return nil - } -} - -// ConfigEnviron configures environment variables. -func ConfigEnviron(env []string) ConfigOption { - return func(cfg *Config) error { - if cfg.configured { - return fmt.Errorf("ConfigEnviron: Config instance already configured") - } - - for _, v := range env { - switch x := strings.IndexByte(v, '='); { - case x < 0: - cfg.env[v] = "" - default: - cfg.env[v[:x]] = v[x+1:] - } - } - return nil - } -} - -// ConfigFS configures a file system used for opening Go source files. If not -// explicitly configured, a default os.DirFS("/") is used on Unix-like -// operating systems. On Windows it will be rooted on the volume where -// runtime.GOROOT() is. -func ConfigFS(fs fs.FS) ConfigOption { - return func(cfg *Config) error { - if cfg.configured { - return fmt.Errorf("ConfigFS: Config instance already configured") - } - - cfg.fs = fs - return nil - } -} - -// ConfigLookup configures a lookup function. -func ConfigLookup(f func(dir, importPath, version string) (fsPath string, err error)) ConfigOption { - return func(cfg *Config) error { - if cfg.configured { - return fmt.Errorf("ConfigLookup: Config instance already configured") - } - - cfg.lookup = f - return nil - } -} - -// ConfigCache configures a cache. -func ConfigCache(c *Cache) ConfigOption { - return func(cfg *Config) error { - if cfg.configured { - return fmt.Errorf("ConfigCache: Config instance already configured") - } - - cfg.cache = c - return nil - } -} - -type importGuard struct { - m map[string]struct{} - stack []string -} - -func newImportGuard() *importGuard { return &importGuard{m: map[string]struct{}{}} } - -// Package represents a Go package. The instance must not be mutated. -type Package struct { - AST map[string]*AST // AST maps fsPaths of individual files to their respective ASTs - FSPath string - GoFiles []fs.FileInfo - ImportPath string - InvalidGoFiles map[string]error // errors for particular files, if any - Name Token - Scope *Scope // Package scope. - Version string - cfg *Config - guard *importGuard - mu sync.Mutex - typeCheck TypeCheck - - isUnsafe bool // ImportPath == "usnafe" - // isChecked bool -} - -// NewPackage returns a Package, possibly cached, for importPath@version or an -// error, if any. The fileFilter argument can be nil, in such case -// DefaultFileFilter is used, which ignores Files with suffix _test.go unless -// withTestFiles is true. -// -// NewPackage is safe for concurrent use by multiple goroutines. -func (c *Config) NewPackage(dir, importPath, version string, fileFilter FileFilter, withTestFiles bool, typeCheck TypeCheck) (pkg *Package, err error) { - return c.newPackage(dir, importPath, version, fileFilter, withTestFiles, typeCheck, newImportGuard()) -} - -func (c *Config) newPackage(dir, importPath, version string, fileFilter FileFilter, withTestFiles bool, typeCheck TypeCheck, guard *importGuard) (pkg *Package, err error) { - if _, ok := guard.m[importPath]; ok { - return nil, fmt.Errorf("import cycle %v", guard.stack) - } - - guard.stack = append(guard.stack, importPath) - fsPath, err := c.lookup(dir, importPath, version) - if err != nil { - return nil, fmt.Errorf("lookup %s: %v", importPath, err) - } - - pat := filepath.Join(fsPath, "*.go") - matches, err := c.glob(pat) - if err != nil { - return nil, fmt.Errorf("glob %s: %v", pat, err) - } - - if len(matches) == 0 { - return nil, fmt.Errorf("no Go files in %s", fsPath) - } - - if fileFilter == nil { - fileFilter = DefaultFileFilter - } - if matches, err = fileFilter(c, importPath, matches, withTestFiles); err != nil { - return nil, fmt.Errorf("matching Go files in %s: %v", fsPath, err) - } - - var k cacheKey - if c.cache != nil { - k = cacheKey{ - buildTagsKey: c.buildTagsKey, - cfg: c, - fsPath: fsPath, - goarch: c.goarch, - goos: c.goos, - gopathKey: c.gopathKey, - goroot: c.goroot, - importPath: importPath, - typeCheck: typeCheck, - withTestFiles: withTestFiles, - } - - c.cache.Lock() // ---------------------------------------- lock - item, ok := c.cache.lru.Get(k) - if ok { - c.cache.Unlock() // ---------------------------- unlock - if pkg = item.wait(); pkg != nil && pkg.matches(&k, matches) { - return pkg, nil - } - } - - item = newCacheItem() - c.cache.lru.Add(k, item) - c.cache.Unlock() // ------------------------------------ unlock - - defer func() { - if pkg != nil && err == nil { - item.set(pkg) - } - }() - } - - r := &Package{ - AST: map[string]*AST{}, - FSPath: fsPath, - ImportPath: importPath, - Scope: newScope(c.universe(), PackageScope), - Version: version, - cfg: c, - guard: guard, - isUnsafe: importPath == "unsafe", - typeCheck: typeCheck, - } - - defer func() { r.guard = nil }() - - sort.Strings(matches) - - defer func() { - sort.Slice(r.GoFiles, func(i, j int) bool { return r.GoFiles[i].Name() < r.GoFiles[j].Name() }) - if err != nil || len(r.InvalidGoFiles) != 0 || typeCheck == TypeCheckNone { - return - } - - //TODO err = r.check(newCtx(c)) - }() - - c.parallel.throttle(func() { - for _, path := range matches { - if err = c.newPackageFile(r, path); err != nil { - return - } - } - }) - return r, err -} - -func (c *Config) newPackageFile(pkg *Package, path string) (err error) { - f, err := c.open(path) - if err != nil { - return fmt.Errorf("opening file %q: %v", path, err) - } - - defer func() { - f.Close() - if err != nil { - if pkg.InvalidGoFiles == nil { - pkg.InvalidGoFiles = map[string]error{} - } - pkg.InvalidGoFiles[path] = err - } - }() - - var fi fs.FileInfo - if fi, err = f.Stat(); err != nil { - return fmt.Errorf("stat %s: %v", path, err) - } - - if !fi.Mode().IsRegular() { - return nil - } - - var b []byte - if b, err = io.ReadAll(f); err != nil { - return fmt.Errorf("reading %s: %v", path, err) - } - - p := newParser(pkg.Scope, path, b, false) - if p.peek(0) == PACKAGE { - tok := Token{p.s.source, p.s.toks[p.ix].ch, int32(p.ix)} - if !c.checkConstraints(tok.Position(), tok.Sep()) { - return nil - } - } - - pkg.GoFiles = append(pkg.GoFiles, fi) - var ast *AST - if ast, err = p.parse(); err != nil { - return nil - } - - pkg.AST[path] = ast - return nil -} - -func (p *Package) matches(k *cacheKey, matches []string) bool { - matched := map[string]struct{}{} - for _, match := range matches { - matched[match] = struct{}{} - } - for _, cachedInfo := range p.GoFiles { - name := cachedInfo.Name() - path := filepath.Join(p.FSPath, name) - if _, ok := matched[path]; !ok { - return false - } - - info, err := k.cfg.stat(path) - if err != nil { - return false - } - - if info.IsDir() || - info.Size() != cachedInfo.Size() || - info.ModTime().After(cachedInfo.ModTime()) || - info.Mode() != cachedInfo.Mode() { - return false - } - } - return true -} - -// ParseFile parses 'b', assuming it comes from 'path' and returns an AST or error, if any. -func ParseFile(path string, b []byte) (*AST, error) { - return newParser(newScope(nil, PackageScope), path, b, false).parse() -} diff --git a/vendor/modernc.org/gc/v3/parser.go b/vendor/modernc.org/gc/v3/parser.go deleted file mode 100644 index e85d1c78d..000000000 --- a/vendor/modernc.org/gc/v3/parser.go +++ /dev/null @@ -1,9415 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // modernc.org/gc/v3 - -import ( - "go/constant" - "go/token" - "path/filepath" - "reflect" - "runtime" - "sort" - "strings" - - "modernc.org/mathutil" - "modernc.org/strutil" -) - -// === RUN TestTypeCheck/GOROOT -// === CONT TestTypeCheck -// all_test.go:1123: TOTAL packages 516, files 2,301, skip 0, ok 516, fail 0 -// all_test.go:1127: pkg count 516, heap 626,182,264 -// --- PASS: TestTypeCheck (2.28s) -// --- PASS: TestTypeCheck/GOROOT (2.12s) - -// all_test.go:1127: pkg count 516, heap 626,153,184 -// all_test.go:1128: pkg count 516, heap 590,057,064 -// all_test.go:1128: pkg count 516, heap 572,015,152 -// all_test.go:1129: pkg count 516, heap 567,709,952 -// all_test.go:1129: pkg count 516, heap 555,500,960 -// all_test.go:1129: pkg count 516, heap 551,777,488 -// all_test.go:1129: pkg count 516, heap 548,683,512 -// all_test.go:1129: pkg count 516, heap 548,447,936 -// all_test.go:1129: pkg count 516, heap 547,480,288 -// all_test.go:1129: pkg count 516, heap 546,915,592 -// all_test.go:1129: pkg count 516, heap 543,393,136 -// all_test.go:1129: pkg count 516, heap 544,638,544 -// all_test.go:1129: pkg count 516, heap 474,343,936 -// all_test.go:1129: pkg count 516, heap 459,353,840 -// all_test.go:1129: pkg count 516, heap 457,275,512 -// all_test.go:1129: pkg count 516, heap 455,355,680 -// all_test.go:1129: pkg count 516, heap 454,663,568 -// all_test.go:1129: pkg count 516, heap 454,581,072 -// all_test.go:1129: pkg count 516, heap 454,607,112 -// all_test.go:1129: pkg count 516, heap 454,709,968 -// all_test.go:1129: pkg count 516, heap 455,312,784 -// all_test.go:1129: pkg count 516, heap 456,016,824 -// all_test.go:1129: pkg count 516, heap 455,954,544 -// all_test.go:1129: pkg count 516, heap 456,016,592 -// all_test.go:1129: pkg count 516, heap 457,121,224 - -// all_test.go:1129: pkg count 516, heap 427,262,960 -// all_test.go:1130: pkg count 516, heap 428,998,600 -// all_test.go:1130: pkg count 551, heap 448,395,152 -// all_test.go:1130: pkg count 551, heap 451,817,616 -// all_test.go:1131: pkg count 551, heap 452,091,200 -// all_test.go:1131: pkg count 551, heap 452,999,840 - -// x 16,603,469 = 892,265,816 á 54 -// x 16,024,194 = 887,787,224 á 55 -// x 16,025,144 = 888,006,760 á 55 -// x 16,025,211 = 823,222,088 á 51 -// x 16,025,281 = 822,404,264 á 51 -// x 14,056,450 = 696,398,872 á 50 -// x 14,056,581 = 696,851,856 á 50 -// x 14,056,453 = 708,480,848 á 50 -// x 14,422,414 = 719,035,680 á 50 -// x 14,423,240 = 717,114,200 á 50 -// x 14,425,901 = 711,567,152 á 49 -// x 14,474,065 = 710,068,032 á 49 -// x 14,481,041 = 710,373,680 á 49 -// x 14,481,767 = 710,408,768 á 49 -// x 14,484,493 = 710,543,264 á 49 -// x 14,461,141 = 706,268,448 á 49 -// x 14,461,182 = 707,678,232 á 49 -// x 14,461,242 = 714,720,336 á 49 -// x 14,461,219 = 797,198,184 á 55 -// x 14,461,496 = 797,214,104 á 55 -// x 14,461,329 = 716,132,376 á 50 -// x 14,461,680 = 711,984,376 á 49 -// x 14,160,586 = 702,969,536 á 50 -// x 14,160,709 = 682,184,664 á 48 -// x 14,160,848 = 673,044,152 á 48 -// x 14,160,317 = 665,980,184 á 47 -// x 14,005,861 = 661,267,672 á 47 -// x 13,983,296 = 660,781,720 á 47 -// x 13,943,950 = 660,175,016 á 47 -// x 13,943,178 = 647,906,568 á 46 -// x 13,924,463 = 648,999,976 á 47 -// x 13,322,751 = 541,059,736 á 41 -// x 12,815,541 = 510,052,400 á 40 -// x 12,815,675 = 506,593,488 á 40 -// x 12,639,779 = 500,965,136 á 40 -// x 12,640,847 = 501,008,776 á 40 -// x 12,603,003 = 499,658,832 á 40 -// x 12,603,001 = 502,473,720 á 40 -// x 12,602,667 = 505,274,416 á 40 -// x 12,603,389 = 505,302,936 á 40 -// x 12,604,481 = 507,314,552 á 40 - -// x 12,590,468 = 454,314,392 á 36 -// x 12,591,896 = 456,980,832 á 36 -// x 12,597,633 = 457,211,632 á 36 -// x 12,597,637 = 458,714,592 á 36 -// x 12,931,431 = 471,180,992 á 36 -// x 12,931,309 = 481,877,912 á 37 -// x 12,933,798 = 482,402,192 á 37 -// x 12,934,587 = 483,606,808 á 37 - -const parserBudget = 1e7 - -var ( - noBack bool - panicBack bool -) - -type visibiliter interface { - Node - Visible() int - setVisible(int32) -} - -type visible struct { - visible int32 // first token index where n is visible -} - -// Visible reports the first token index where n is visible (in scope). Applies -// to local scopes only. -func (n *visible) Visible() int { return int(n.visible) } - -func (n *visible) setVisible(i int32) { n.visible = i } - -type named struct { - n visibiliter - declTok Token -} - -type ScopeKind int - -const ( - scZero ScopeKind = iota - UniverseScope - PackageScope - FileScope - OtherScope -) - -type Scope struct { - nodes map[string]named - parent *Scope - - kind ScopeKind -} - -func newScope(parent *Scope, kind ScopeKind) *Scope { return &Scope{parent: parent, kind: kind} } - -func (s *Scope) Iterate(f func(name string, n Node) (stop bool)) { - for name, v := range s.nodes { - if f(name, v.n) { - return - } - } -} - -func (s *Scope) Kind() ScopeKind { return s.kind } - -func (s *Scope) Parent() *Scope { return s.parent } - -func (s *Scope) declare(nm Token, n visibiliter, visible int32, p *parser, initOK bool) (r named) { - snm := nm.Src() - switch snm { - case "_": - return r - case "init": - if s.kind == PackageScope { - if p != nil && !initOK && p.reportDeclarationErrors { - p.err(nm.Position(), "in the package block, the identifier init may only be used for init function declarations") - } - return r - } - } - - if ex, ok := s.nodes[snm]; ok { - return ex - } - - if s.nodes == nil { - s.nodes = map[string]named{} - } - // trc("%v: add %s %p", nm.Position(), snm, s) - n.setVisible(visible) - s.nodes[snm] = named{n, nm} - return r -} - -func (s *Scope) lookup(id Token) (in *Scope, r named) { - nm := id.Src() - ix := int(id.index) - for s != nil { - switch s.kind { - case PackageScope, UniverseScope: - ix = -1 - } - - sc, ok := s.nodes[nm] - if ok && (ix < 0 || ix > sc.n.Visible()) { - return s, sc - } - - s = s.parent - } - return nil, r -} - -type lexicalScoper struct{ s *Scope } - -func newLexicalScoper(s *Scope) lexicalScoper { return lexicalScoper{s} } - -func (n *lexicalScoper) LexicalScope() *Scope { return n.s } - -// Node is an item of the CST tree. -type Node interface { - Position() token.Position - Source(full bool) string -} - -var hooks = strutil.PrettyPrintHooks{ - reflect.TypeOf(Token{}): func(f strutil.Formatter, v interface{}, prefix, suffix string) { - t := v.(Token) - if !t.IsValid() { - return - } - - pos := t.Position() - if pos.Filename != "" { - pos.Filename = filepath.Base(pos.Filename) - } - f.Format(string(prefix)+"%10s %q %q\t(%v:)"+string(suffix), tokSource(t.Ch()), t.Sep(), t.Src(), pos) - }, -} - -func dump(n Node) string { return strutil.PrettyString(n, "", "", hooks) } - -// NodeSource returns the source text of 'n'. If 'full' is false, every non -// empty separator is replaced by a single space. Nodes found in 'kill' are -// skipped, transitively. -func NodeSource(n Node, full bool, kill map[Node]struct{}) string { - return nodeSource2(n, full, kill) -} - -func nodeSource(n interface{}, full bool) string { - return nodeSource2(n, full, nil) -} - -func nodeSource2(n interface{}, full bool, kill map[Node]struct{}) string { - var a []int32 - var t Token - nodeSource0(&t.source, &a, n, kill) - if len(a) == 0 { - return "" - } - - var b strings.Builder - sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) - for _, v := range a { - t.index = v - t.ch = t.source.toks[t.index].ch - b.WriteString(t.Source(full)) - } - return b.String() -} - -func nodeSource0(ps **source, a *[]int32, n interface{}, kill map[Node]struct{}) { - if x, ok := n.(Node); ok { - if _, ok := kill[x]; ok { - return - } - } - - switch x := n.(type) { - case nil: - // nop - case Token: - if x.IsValid() { - *ps = x.source - *a = append(*a, x.index) - } - case *BasicLitNode: - if x.IsValid() { - *ps = x.source - *a = append(*a, x.index) - } - default: - t := reflect.TypeOf(n) - v := reflect.ValueOf(n) - if v.IsZero() { - break - } - - switch t.Kind() { - case reflect.Pointer: - nodeSource0(ps, a, v.Elem().Interface(), kill) - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if token.IsExported(t.Field(i).Name) { - nodeSource0(ps, a, v.Field(i).Interface(), kill) - } - } - case reflect.Slice: - for i := 0; i < v.Len(); i++ { - nodeSource0(ps, a, v.Index(i).Interface(), kill) - } - default: - panic(todo("", t.Name(), t.Kind())) - } - } -} - -type AST struct { - EOF Token - FileScope *Scope - SourceFile *SourceFileNode - packageScope *Scope // For the individual file, enables parallelism, consolidated by Package.check() -} - -func (n *AST) Source(full bool) string { return nodeSource(n, full) } - -func (n *AST) Position() (r token.Position) { - if n == nil { - return r - } - return n.SourceFile.Position() -} - -type parser struct { - a *analyzer - fileScope *Scope - maxBackOrigin string - maxBackRange [2]int - packageScope *Scope - path string - s *scanner - sc *Scope - - backs int - budget int - ix int - maxBack int - maxIx int - - isClosed bool - record bool - reportDeclarationErrors bool -} - -func newParser(pkgScope *Scope, path string, src []byte, record bool) *parser { - return &parser{ - a: newAnalyzer(), - budget: parserBudget, - fileScope: newScope(pkgScope, FileScope), - packageScope: pkgScope, - path: path, - record: record, - s: newScanner(path, src), - sc: pkgScope, - } -} - -func (p *parser) c() token.Token { return p.peek(0) } -func (p *parser) closeScope() { p.sc = p.sc.parent } -func (p *parser) errPosition() (r token.Position) { return p.s.toks[p.maxIx].position(p.s.source) } -func (p *parser) openScope() { p.sc = newScope(p.sc, OtherScope) } - -func (p *parser) pos() (r token.Position) { - return p.s.toks[mathutil.MinInt32(int32(p.ix), int32(len(p.s.toks)-1))].position(p.s.source) -} - -func (p *parser) err(pos token.Position, msg string, args ...interface{}) { - p.s.errs.err(pos, msg, args...) -} - -func (p *parser) declare(s *Scope, nm Token, n visibiliter, visible int32, initOK bool) { - if ex := s.declare(nm, n, visible, p, initOK); ex.declTok.IsValid() && p.reportDeclarationErrors { - p.err(nm.Position(), "%s redeclared, previous declaration at %v:", nm.Src(), ex.declTok.Position()) - } -} - -func (p *parser) consume() (r Token) { - r = Token{p.s.source, p.s.toks[p.ix].ch, int32(p.ix)} - p.ix++ - p.budget-- - return r -} - -func (p *parser) accept(t token.Token) (r Token, _ bool) { - if p.c() == t { - return p.consume(), true - } - return r, false -} - -func (p *parser) expect(t token.Token) (r Token) { - var ok bool - if r, ok = p.accept(t); !ok { - p.isClosed = true - } - return r -} - -func (p *parser) peek(n int) token.Token { - for p.ix+n >= len(p.s.toks) { - if p.budget <= 0 || p.isClosed { - return EOF - } - - p.s.scan() - if p.s.isClosed { - p.isClosed = true - } - } - p.maxIx = mathutil.Max(p.maxIx, p.ix) - return token.Token(p.s.toks[p.ix+n].ch) -} - -func (p *parser) recordBacktrack(ix int, record bool) { - delta := p.ix - ix - p.backs += delta - if delta > p.maxBack { - p.maxBack = delta - p.maxBackRange = [2]int{ix, p.ix} - p.maxBackOrigin = origin(3) - } - p.ix = ix - if p.record && record { - if _, _, line, ok := runtime.Caller(2); ok { - p.a.record(line, delta) - } - } -} - -func (p *parser) back(ix int) { - p.recordBacktrack(ix, true) - if p.isClosed { - return - } - - if noBack { - p.isClosed = true - } - if panicBack { - panic(todo("%v: (%v:)", p.errPosition(), origin(2))) - } -} - -func (p *parser) parse() (ast *AST, err error) { - if p.c() != PACKAGE { - p.s.errs.err(p.errPosition(), "syntax error") - return nil, p.s.errs - } - - sourceFile := p.sourceFile() - if p.budget <= 0 { - return nil, errorf("%s: resources exhausted", p.path) - } - - if eof, ok := p.accept(EOF); ok && p.ix == len(p.s.toks) { - return &AST{packageScope: p.packageScope, FileScope: p.fileScope, SourceFile: sourceFile, EOF: eof}, p.s.errs.Err() - } - - p.s.errs.err(p.errPosition(), "syntax error") - return nil, p.s.errs -} - -type BinaryExpressionNode struct { - LHS Expression - Op Token - RHS Expression - - typeCache - valueCache -} - -// Position implements Node. -func (n *BinaryExpressionNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LHS.Position() -} - -// Source implements Node. -func (n *BinaryExpressionNode) Source(full bool) string { return nodeSource(n, full) } - -func (p *parser) additiveExpression(preBlock bool) (r Expression) { - var multiplicativeExpression Expression - // ebnf.Sequence MultiplicativeExpression { ( "+" | "-" | "|" | "^" ) MultiplicativeExpression } ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name MultiplicativeExpression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if multiplicativeExpression = p.multiplicativeExpression(preBlock); multiplicativeExpression == nil { - p.back(ix) - return nil - } - // *ebnf.Repetition { ( "+" | "-" | "|" | "^" ) MultiplicativeExpression } ctx [] - r = multiplicativeExpression - _0: - { - var op Token - var multiplicativeExpression Expression - switch p.c() { - case ADD, OR, SUB, XOR: - // ebnf.Sequence ( "+" | "-" | "|" | "^" ) MultiplicativeExpression ctx [ADD, OR, SUB, XOR] - // *ebnf.Group ( "+" | "-" | "|" | "^" ) ctx [ADD, OR, SUB, XOR] - // ebnf.Alternative "+" | "-" | "|" | "^" ctx [ADD, OR, SUB, XOR] - op = p.consume() - // *ebnf.Name MultiplicativeExpression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if multiplicativeExpression = p.multiplicativeExpression(preBlock); multiplicativeExpression == nil { - p.back(ix) - goto _1 - } - default: - p.back(ix) - goto _1 - } - r = &BinaryExpressionNode{LHS: r, Op: op, RHS: multiplicativeExpression} - goto _0 - } - _1: - } - } - return r -} - -// AliasDeclNode represents the production -// -// AliasDecl = identifier "=" Type . -type AliasDeclNode struct { - IDENT Token - ASSIGN Token - TypeNode Type - - visible -} - -// Source implements Node. -func (n *AliasDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *AliasDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IDENT.Position() -} - -func (p *parser) aliasDecl() (r *AliasDeclNode) { - var ( - identTok Token - assignTok Token - typeNode Type - ) - // ebnf.Sequence identifier "=" Type ctx [IDENT] - { - if p.peek(1) != ASSIGN { - return nil - } - ix := p.ix - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - // *ebnf.Token "=" ctx [ASSIGN] - assignTok = p.expect(ASSIGN) - // *ebnf.Name Type ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - r = &AliasDeclNode{ - IDENT: identTok, - ASSIGN: assignTok, - TypeNode: typeNode, - } - p.declare(p.sc, identTok, r, int32(p.ix), false) - return r -} - -// ArgumentsNode represents the production -// -// Arguments = "(" [ Expression ] ")" . -type ArgumentsNode struct { - LPAREN Token - Expression Expression - RPAREN Token -} - -// Source implements Node. -func (n *ArgumentsNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ArgumentsNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LPAREN.Position() -} - -// Arguments1Node represents the production -// -// Arguments = "(" [ ( Expression | Type [ "," Expression ] ) [ "..." ] [ "," ] ] ")" . -type Arguments1Node struct { - LPAREN Token - Expression Expression - TypeNode Type - COMMA Token - ELLIPSIS Token - COMMA2 Token - RPAREN Token -} - -// Source implements Node. -func (n *Arguments1Node) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *Arguments1Node) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LPAREN.Position() -} - -// Arguments2Node represents the production -// -// Arguments = "(" ExpressionList ")" . -type Arguments2Node struct { - LPAREN Token - ExpressionList *ExpressionListNode - RPAREN Token -} - -// Source implements Node. -func (n *Arguments2Node) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *Arguments2Node) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LPAREN.Position() -} - -// Arguments3Node represents the production -// -// Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" . -type Arguments3Node struct { - LPAREN Token - ExpressionList *ExpressionListNode - TypeNode Type - COMMA Token - ELLIPSIS Token - COMMA2 Token - RPAREN Token -} - -// Source implements Node. -func (n *Arguments3Node) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *Arguments3Node) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LPAREN.Position() -} - -func (p *parser) arguments() Node { - var ( - ok bool - lparenTok Token - expressionList *ExpressionListNode - typeNode Type - commaTok Token - ellipsisTok Token - comma2Tok Token - rparenTok Token - ) - // ebnf.Sequence "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" ctx [LPAREN] - { - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Option [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // ebnf.Sequence ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Group ( ExpressionList | Type [ "," ExpressionList ] ) ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - // ebnf.Alternative ExpressionList | Type [ "," ExpressionList ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - switch p.c() { - case ADD, AND, CHAR, FLOAT, IMAG, INT, NOT, STRING, SUB, XOR: // 0 - // *ebnf.Name ExpressionList ctx [ADD, AND, CHAR, FLOAT, IMAG, INT, NOT, STRING, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - goto _2 - } - break - _2: - expressionList = nil - p.back(ix) - goto _0 - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: // 0 1 - // *ebnf.Name ExpressionList ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if expressionList = p.expressionList(false); expressionList == nil { - goto _4 - } - break - _4: - expressionList = nil - // ebnf.Sequence Type [ "," ExpressionList ] ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _5 - } - // *ebnf.Option [ "," ExpressionList ] ctx [] - switch p.c() { - case COMMA: - // ebnf.Sequence "," ExpressionList ctx [COMMA] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _6 - } - ix := p.ix - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _6 - } - } - } - goto _7 - _6: - commaTok = Token{} - expressionList = nil - _7: - } - break - _5: - commaTok = Token{} - expressionList = nil - typeNode = nil - p.back(ix) - goto _0 - default: - p.back(ix) - goto _0 - } - // *ebnf.Option [ "..." ] ctx [] - switch p.c() { - case ELLIPSIS: - // *ebnf.Token "..." ctx [ELLIPSIS] - ellipsisTok = p.expect(ELLIPSIS) - } - // *ebnf.Option [ "," ] ctx [] - switch p.c() { - case COMMA: - // *ebnf.Token "," ctx [COMMA] - comma2Tok = p.expect(COMMA) - } - } - } - goto _1 - _0: - comma2Tok = Token{} - ellipsisTok = Token{} - expressionList = nil - _1: - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - return nil - } - } - switch expressionList.Len() { - case 0, 1: - if typeNode == nil && !commaTok.IsValid() && !ellipsisTok.IsValid() && !comma2Tok.IsValid() { - return &ArgumentsNode{ - LPAREN: lparenTok, - Expression: expressionList.first(), - RPAREN: rparenTok, - } - } - - return &Arguments1Node{ - LPAREN: lparenTok, - Expression: expressionList.first(), - TypeNode: typeNode, - COMMA: commaTok, - ELLIPSIS: ellipsisTok, - COMMA2: comma2Tok, - RPAREN: rparenTok, - } - default: - if typeNode == nil && !commaTok.IsValid() && !ellipsisTok.IsValid() && !comma2Tok.IsValid() { - return &Arguments2Node{ - LPAREN: lparenTok, - ExpressionList: expressionList, - RPAREN: rparenTok, - } - } - - return &Arguments3Node{ - LPAREN: lparenTok, - ExpressionList: expressionList, - TypeNode: typeNode, - COMMA: commaTok, - ELLIPSIS: ellipsisTok, - COMMA2: comma2Tok, - RPAREN: rparenTok, - } - } -} - -func (p *parser) arrayLength() Expression { - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - return p.expression(false) -} - -// ArrayTypeNode represents the production -// -// ArrayType = "[" ArrayLength "]" ElementType . -type ArrayTypeNode struct { - LBRACK Token - ArrayLength Expression - RBRACK Token - ElementType Type -} - -// Source implements Node. -func (n *ArrayTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ArrayTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACK.Position() -} - -func (p *parser) arrayType() *ArrayTypeNode { - var ( - ok bool - lbrackTok Token - arrayLength Expression - rbrackTok Token - elementType Type - ) - // ebnf.Sequence "[" ArrayLength "]" ElementType ctx [LBRACK] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - return nil - } - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Name ArrayLength ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if arrayLength = p.arrayLength(); arrayLength == nil { - p.back(ix) - return nil - } - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - return nil - } - // *ebnf.Name ElementType ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if elementType = p.type1(); elementType == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &ArrayTypeNode{ - LBRACK: lbrackTok, - ArrayLength: arrayLength, - RBRACK: rbrackTok, - ElementType: elementType, - } -} - -// AssignmentNode represents the production -// -// Assignment = ExpressionList ( "=" | "+=" | "-=" | "|=" | "^=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | "&=" | "&^=" ) ExpressionList . -type AssignmentNode struct { - ExpressionList *ExpressionListNode - Op Token - ExpressionList2 *ExpressionListNode -} - -// Source implements Node. -func (n *AssignmentNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *AssignmentNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) assignment(expressionList *ExpressionListNode, preBlock bool) *AssignmentNode { - var ( - op Token - expressionList2 *ExpressionListNode - ) - // ebnf.Sequence ( "=" | "+=" | "-=" | "|=" | "^=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | "&=" | "&^=" ) ExpressionList ctx [ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ASSIGN, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN] - { - ix := p.ix - // *ebnf.Group ( "=" | "+=" | "-=" | "|=" | "^=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | "&=" | "&^=" ) ctx [ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ASSIGN, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN] - // ebnf.Alternative "=" | "+=" | "-=" | "|=" | "^=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | "&=" | "&^=" ctx [ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ASSIGN, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN] - op = p.consume() - // *ebnf.Name ExpressionList ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expressionList2 = p.expressionList(preBlock); expressionList2 == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &AssignmentNode{ - ExpressionList: expressionList, - Op: op, - ExpressionList2: expressionList2, - } -} - -// BasicLitNode represents the production -// -// BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . -type BasicLitNode struct { - Token - ctx *ctx -} - -//TODO- // Source implements Node. -//TODO- func (n *BasicLitNode) Source(full bool) string { return nodeSource(n, full) } -//TODO- -//TODO- // Position implements Node. -//TODO- func (n *BasicLitNode) Position() (r token.Position) { -//TODO- if !n.IsValid() { -//TODO- return r -//TODO- } -//TODO- -//TODO- return Token(*n).Position() -//TODO- } -//TODO- -//TODO- func (n *BasicLitNode) Ch() token.Token { return Token(*n).Ch() } -//TODO- func (n *BasicLitNode) IsValid() bool { return Token(*n).IsValid() } - -func (p *parser) basicLit() Expression { - // ebnf.Alternative int_lit | float_lit | imaginary_lit | rune_lit | string_lit ctx [CHAR, FLOAT, IMAG, INT, STRING] - t := p.consume() - v := constant.MakeFromLiteral(t.Src(), token.Token(t.ch), 0) - if v.Kind() == constant.Unknown { - p.err(t.Position(), "invalid literal: %s", t.Src()) - } - return &BasicLitNode{Token: t} -} - -// BlockNode represents the production -// -// Block = "{" StatementList "}" . -type BlockNode struct { - LBRACE Token - StatementList *StatementListNode - RBRACE Token -} - -// Source implements Node. -func (n *BlockNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *BlockNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACE.Position() -} - -func (p *parser) block(rx *ParametersNode, s *SignatureNode) *BlockNode { - var ( - ok bool - lbraceTok Token - statementList *StatementListNode - rbraceTok Token - ) - // ebnf.Sequence "{" StatementList "}" ctx [LBRACE] - { - p.openScope() - - defer p.closeScope() - - ix := p.ix - // *ebnf.Token "{" ctx [LBRACE] - lbraceTok = p.expect(LBRACE) - if rx != nil { - rx.declare(p, p.sc) - } - if s != nil { - s.Parameters.declare(p, p.sc) - if s.Result != nil { - s.Result.Parameters.declare(p, p.sc) - } - } - // *ebnf.Name StatementList ctx [] - switch p.c() { - case ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, SEMICOLON, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */ : - if statementList = p.statementList(); statementList == nil { - p.back(ix) - return nil - } - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - return nil - } - } - return &BlockNode{ - LBRACE: lbraceTok, - StatementList: statementList, - RBRACE: rbraceTok, - } -} - -// BreakStmtNode represents the production -// -// BreakStmt = "break" [ Label ] . -type BreakStmtNode struct { - BREAK Token - Label *LabelNode -} - -// Source implements Node. -func (n *BreakStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *BreakStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.BREAK.Position() -} - -func (p *parser) breakStmt() *BreakStmtNode { - var ( - breakTok Token - label *LabelNode - ) - // ebnf.Sequence "break" [ Label ] ctx [BREAK] - { - // *ebnf.Token "break" ctx [BREAK] - breakTok = p.expect(BREAK) - // *ebnf.Option [ Label ] ctx [] - switch p.c() { - case IDENT: - // *ebnf.Name Label ctx [IDENT] - if label = p.label(); label == nil { - goto _0 - } - } - goto _1 - _0: - label = nil - _1: - } - return &BreakStmtNode{ - BREAK: breakTok, - Label: label, - } -} - -func (p *parser) channel() Expression { - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - return p.expression(false) -} - -// ChannelTypeNode represents the production -// -// ChannelType = ( "chan" "<-" | "chan" | "<-" "chan" ) ElementType . -type ChannelTypeNode struct { - CHAN Token - ARROW Token - ElementType Type -} - -// Source implements Node. -func (n *ChannelTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ChannelTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.ARROW.IsValid() && n.ARROW.index < n.CHAN.index { - return n.ARROW.Position() - } - - return n.CHAN.Position() -} - -func (p *parser) channelType() *ChannelTypeNode { - var ( - chanTok Token - arrowTok Token - elementType Type - ) - // ebnf.Sequence ( "chan" "<-" | "chan" | "<-" "chan" ) ElementType ctx [ARROW, CHAN] - { - ix := p.ix - // *ebnf.Group ( "chan" "<-" | "chan" | "<-" "chan" ) ctx [ARROW, CHAN] - // ebnf.Alternative "chan" "<-" | "chan" | "<-" "chan" ctx [ARROW, CHAN] - switch p.c() { - case CHAN: // 0 1 - // ebnf.Sequence "chan" "<-" ctx [CHAN] - { - if p.peek(1) != ARROW { - goto _0 - } - // *ebnf.Token "chan" ctx [CHAN] - chanTok = p.expect(CHAN) - // *ebnf.Token "<-" ctx [ARROW] - arrowTok = p.expect(ARROW) - } - break - _0: - arrowTok = Token{} - chanTok = Token{} - // *ebnf.Token "chan" ctx [CHAN] - chanTok = p.expect(CHAN) - break - p.back(ix) - return nil - case ARROW: // 2 - // ebnf.Sequence "<-" "chan" ctx [ARROW] - { - if p.peek(1) != CHAN { - goto _2 - } - // *ebnf.Token "<-" ctx [ARROW] - arrowTok = p.expect(ARROW) - // *ebnf.Token "chan" ctx [CHAN] - chanTok = p.expect(CHAN) - } - break - _2: - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - // *ebnf.Name ElementType ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if elementType = p.type1(); elementType == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &ChannelTypeNode{ - CHAN: chanTok, - ARROW: arrowTok, - ElementType: elementType, - } -} - -// CommCaseNode represents the production -// -// CommCase = "case" ( SendStmt | RecvStmt ) | "default" . -type CommCaseNode struct { - CASE Token - SendStmt *SendStmtNode - RecvStmt *RecvStmtNode - DEFAULT Token -} - -// Source implements Node. -func (n *CommCaseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *CommCaseNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) commCase() *CommCaseNode { - var ( - caseTok Token - sendStmt *SendStmtNode - recvStmt *RecvStmtNode - defaultTok Token - ) - // ebnf.Alternative "case" ( SendStmt | RecvStmt ) | "default" ctx [CASE, DEFAULT] - switch p.c() { - case CASE: // 0 - // ebnf.Sequence "case" ( SendStmt | RecvStmt ) ctx [CASE] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _0 - } - ix := p.ix - // *ebnf.Token "case" ctx [CASE] - caseTok = p.expect(CASE) - // *ebnf.Group ( SendStmt | RecvStmt ) ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - // ebnf.Alternative SendStmt | RecvStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: // 0 1 - // *ebnf.Name SendStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if sendStmt = p.sendStmt(); sendStmt == nil { - goto _2 - } - break - _2: - sendStmt = nil - // *ebnf.Name RecvStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if recvStmt = p.recvStmt(); recvStmt == nil { - goto _3 - } - break - _3: - recvStmt = nil - p.back(ix) - goto _0 - default: - p.back(ix) - goto _0 - } - } - break - _0: - caseTok = Token{} - return nil - case DEFAULT: // 1 - // *ebnf.Token "default" ctx [DEFAULT] - defaultTok = p.expect(DEFAULT) - default: - return nil - } - return &CommCaseNode{ - CASE: caseTok, - SendStmt: sendStmt, - RecvStmt: recvStmt, - DEFAULT: defaultTok, - } -} - -// CommClauseNode represents the production -// -// CommClause = CommCase ":" StatementList . -type CommClauseNode struct { - CommCase *CommCaseNode - COLON Token - StatementList *StatementListNode -} - -// Source implements Node. -func (n *CommClauseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *CommClauseNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.CommCase.Position() -} - -func (p *parser) commClause() *CommClauseNode { - var ( - ok bool - commCase *CommCaseNode - colonTok Token - statementList *StatementListNode - ) - // ebnf.Sequence CommCase ":" StatementList ctx [CASE, DEFAULT] - { - p.openScope() - - defer p.closeScope() - - ix := p.ix - // *ebnf.Name CommCase ctx [CASE, DEFAULT] - if commCase = p.commCase(); commCase == nil { - p.back(ix) - return nil - } - // *ebnf.Token ":" ctx [] - if colonTok, ok = p.accept(COLON); !ok { - p.back(ix) - return nil - } - // *ebnf.Name StatementList ctx [] - switch p.c() { - case ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, SEMICOLON, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */ : - if statementList = p.statementList(); statementList == nil { - p.back(ix) - return nil - } - } - } - return &CommClauseNode{ - CommCase: commCase, - COLON: colonTok, - StatementList: statementList, - } -} - -// CompositeLitNode represents the production -// -// CompositeLit = LiteralType LiteralValue . -type CompositeLitNode struct { - LiteralType Node - LiteralValue *LiteralValueNode - - typeCache -} - -// Source implements Node. -func (n *CompositeLitNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *CompositeLitNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LiteralType.Position() -} - -func (p *parser) compositeLit() *CompositeLitNode { - var ( - literalType Node - literalValue *LiteralValueNode - ) - // ebnf.Sequence LiteralType LiteralValue ctx [LBRACK, MAP, STRUCT] - { - ix := p.ix - // *ebnf.Name LiteralType ctx [LBRACK, MAP, STRUCT] - if literalType = p.literalType(); literalType == nil { - p.back(ix) - return nil - } - // *ebnf.Name LiteralValue ctx [] - switch p.c() { - case LBRACE: - if literalValue = p.literalValue(); literalValue == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &CompositeLitNode{ - LiteralType: literalType, - LiteralValue: literalValue, - } -} - -func (p *parser) condition(preBlock bool) Expression { - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - return p.expression(preBlock) -} - -// ConstSpecListNode represents the production -// -// ConstSpecListNode = { ConstSpec ";" } . -type ConstSpecListNode struct { - ConstSpec Node - SEMICOLON Token - List *ConstSpecListNode -} - -// Source implements Node. -func (n *ConstSpecListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ConstSpecListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.ConstSpec.Position() -} - -// ConstDeclNode represents the production -// -// ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . -type ConstDeclNode struct { - CONST Token - LPAREN Token - ConstSpec Node - RPAREN Token -} - -// Source implements Node. -func (n *ConstDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ConstDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.CONST.Position() -} - -func (p *parser) constDecl() *ConstDeclNode { - var ( - ok bool - constTok Token - constSpec Node - lparenTok Token - list *ConstSpecListNode - rparenTok Token - iota int64 - ) - // ebnf.Sequence "const" ( ConstSpec | "(" { ConstSpec ";" } [ ConstSpec ] ")" ) ctx [CONST] - { - switch p.peek(1) { - case IDENT, LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Token "const" ctx [CONST] - constTok = p.expect(CONST) - // *ebnf.Group ( ConstSpec | "(" { ConstSpec ";" } [ ConstSpec ] ")" ) ctx [IDENT, LPAREN] - // ebnf.Alternative ConstSpec | "(" { ConstSpec ";" } [ ConstSpec ] ")" ctx [IDENT, LPAREN] - switch p.c() { - case IDENT: // 0 - // *ebnf.Name ConstSpec ctx [IDENT] - if constSpec = p.constSpec(iota); constSpec == nil { - goto _0 - } - list = &ConstSpecListNode{ - ConstSpec: constSpec, - } - break - _0: - constSpec = nil - p.back(ix) - return nil - case LPAREN: // 1 - // ebnf.Sequence "(" { ConstSpec ";" } [ ConstSpec ] ")" ctx [LPAREN] - { - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Repetition { ConstSpec ";" } ctx [] - var item *ConstSpecListNode - _4: - { - var constSpec Node - var semicolonTok Token - switch p.c() { - case IDENT: - // ebnf.Sequence ConstSpec ";" ctx [IDENT] - ix := p.ix - // *ebnf.Name ConstSpec ctx [IDENT] - if constSpec = p.constSpec(iota); constSpec == nil { - p.back(ix) - goto _5 - } - if p.c() == RPAREN { - next := &ConstSpecListNode{ - ConstSpec: constSpec, - } - if item != nil { - item.List = next - } - item = next - if list == nil { - list = item - } - break - } - - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _5 - } - next := &ConstSpecListNode{ - ConstSpec: constSpec, - SEMICOLON: semicolonTok, - } - iota++ - if item != nil { - item.List = next - } - item = next - if list == nil { - list = item - } - goto _4 - } - _5: - } - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - goto _2 - } - } - break - _2: - lparenTok = Token{} - rparenTok = Token{} - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - } - if list != nil && list.List == nil && !list.SEMICOLON.IsValid() { - return &ConstDeclNode{ - CONST: constTok, - LPAREN: lparenTok, - ConstSpec: list.ConstSpec, - RPAREN: rparenTok, - } - } - - return &ConstDeclNode{ - CONST: constTok, - LPAREN: lparenTok, - ConstSpec: list, - RPAREN: rparenTok, - } -} - -// ConstSpecNode represents the production -// -// ConstSpec = Identifier [ [ Type ] "=" Expression ] . -type ConstSpecNode struct { - IDENT Token - TypeNode Type - ASSIGN Token - Expression Expression - - iota int64 - visible - - guard -} - -// Source implements Node. -func (n *ConstSpecNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ConstSpecNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IDENT.Position() -} - -// ConstSpec2Node represents the production -// -// ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . -type ConstSpec2Node struct { - IdentifierList *IdentifierListNode - TypeNode Type - ASSIGN Token - ExpressionList *ExpressionListNode - - iota int64 - - visible -} - -// Source implements Node. -func (n *ConstSpec2Node) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ConstSpec2Node) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IdentifierList.Position() -} - -func (p *parser) constSpec(iota int64) Node { - var ( - ok bool - identifierList *IdentifierListNode - typeNode Type - assignTok Token - expressionList *ExpressionListNode - ) - // ebnf.Sequence IdentifierList [ [ Type ] "=" ExpressionList ] ctx [IDENT] - { - ix := p.ix - // *ebnf.Name IdentifierList ctx [IDENT] - if identifierList = p.identifierList(); identifierList == nil { - p.back(ix) - return nil - } - // *ebnf.Option [ [ Type ] "=" ExpressionList ] ctx [] - switch p.c() { - case ARROW, ASSIGN, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - // ebnf.Sequence [ Type ] "=" ExpressionList ctx [ARROW, ASSIGN, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - // *ebnf.Option [ Type ] ctx [ARROW, ASSIGN, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - goto _2 - } - } - goto _3 - _2: - typeNode = nil - _3: - // *ebnf.Token "=" ctx [] - if assignTok, ok = p.accept(ASSIGN); !ok { - p.back(ix) - goto _0 - } - // *ebnf.Name ExpressionList ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _0 - } - default: - p.back(ix) - goto _0 - } - } - } - goto _1 - _0: - assignTok = Token{} - expressionList = nil - typeNode = nil - _1: - } - sc := p.sc - visible := int32(p.ix) - if expressionList.Len() < 2 && identifierList.Len() < 2 { - r := &ConstSpecNode{ - IDENT: identifierList.first(), - TypeNode: typeNode, - ASSIGN: assignTok, - Expression: expressionList.first(), - iota: iota, - } - ids := identifierList.Len() - exprs := expressionList.Len() - if exprs != 0 && ids != exprs { - p.err(r.ASSIGN.Position(), "different number of identifiers and expressions: %v %v", ids, exprs) - } - for l := identifierList; l != nil; l = l.List { - p.declare(sc, l.IDENT, r, visible, false) - } - return r - } - - r := &ConstSpec2Node{ - IdentifierList: identifierList, - TypeNode: typeNode, - ASSIGN: assignTok, - ExpressionList: expressionList, - iota: iota, - } - ids := r.IdentifierList.Len() - exprs := r.ExpressionList.Len() - if exprs != 0 && ids != exprs { - p.err(r.ASSIGN.Position(), "different number of identifiers and expressions: %v %v", ids, exprs) - } - for l := r.IdentifierList; l != nil; l = l.List { - p.declare(sc, l.IDENT, r, visible, false) - } - return r -} - -// ContinueStmtNode represents the production -// -// ContinueStmt = "continue" [ Label ] . -type ContinueStmtNode struct { - CONTINUE Token - Label *LabelNode -} - -// Source implements Node. -func (n *ContinueStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ContinueStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.CONTINUE.Position() -} - -func (p *parser) continueStmt() *ContinueStmtNode { - var ( - continueTok Token - label *LabelNode - ) - // ebnf.Sequence "continue" [ Label ] ctx [CONTINUE] - { - // *ebnf.Token "continue" ctx [CONTINUE] - continueTok = p.expect(CONTINUE) - // *ebnf.Option [ Label ] ctx [] - switch p.c() { - case IDENT: - // *ebnf.Name Label ctx [IDENT] - if label = p.label(); label == nil { - goto _0 - } - } - goto _1 - _0: - label = nil - _1: - } - return &ContinueStmtNode{ - CONTINUE: continueTok, - Label: label, - } -} - -// ConversionNode represents the production -// -// Conversion = Type "(" Expression [ "," ] ")" . -type ConversionNode struct { - TypeNode Type - LPAREN Token - Expression Expression - COMMA Token - RPAREN Token - - valueCache -} - -// Source implements Node. -func (n *ConversionNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ConversionNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TypeNode.Position() -} - -func (p *parser) conversion() *ConversionNode { - var ( - ok bool - typeNode Type - lparenTok Token - expression Expression - commaTok Token - rparenTok Token - ) - // ebnf.Sequence Type "(" Expression [ "," ] ")" ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - return nil - } - // *ebnf.Token "(" ctx [] - if lparenTok, ok = p.accept(LPAREN); !ok { - p.back(ix) - return nil - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression = p.expression(false); expression == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Option [ "," ] ctx [] - switch p.c() { - case COMMA: - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - return nil - } - } - return &ConversionNode{ - TypeNode: typeNode, - LPAREN: lparenTok, - Expression: expression, - COMMA: commaTok, - RPAREN: rparenTok, - } -} - -func (p *parser) declaration() Node { - // ebnf.Alternative ConstDecl | TypeDecl | VarDecl ctx [CONST, TYPE, VAR] - switch p.c() { - case CONST: // 0 - // *ebnf.Name ConstDecl ctx [CONST] - return p.constDecl() - case TYPE: // 1 - // *ebnf.Name TypeDecl ctx [TYPE] - return p.typeDecl() - case VAR: // 2 - // *ebnf.Name VarDecl ctx [VAR] - return p.varDecl() - default: - return nil - } -} - -// DeferStmtNode represents the production -// -// DeferStmt = "defer" Expression . -type DeferStmtNode struct { - DEFER Token - Expression Expression -} - -// Source implements Node. -func (n *DeferStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *DeferStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.DEFER.Position() -} - -func (p *parser) deferStmt() *DeferStmtNode { - var ( - deferTok Token - expression Expression - ) - // ebnf.Sequence "defer" Expression ctx [DEFER] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - return nil - } - ix := p.ix - // *ebnf.Token "defer" ctx [DEFER] - deferTok = p.expect(DEFER) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression == nil { - p.back(ix) - return nil - } - } - return &DeferStmtNode{ - DEFER: deferTok, - Expression: expression, - } -} - -func (p *parser) element() Expression { - var ( - expression Expression - literalValue *LiteralValueNode - ) - // ebnf.Alternative Expression | LiteralValue ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: // 0 - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression != nil { - return expression - } - case LBRACE: // 1 - // *ebnf.Name LiteralValue ctx [LBRACE] - if literalValue = p.literalValue(); literalValue != nil { - return literalValue - } - } - return nil -} - -// EmbeddedFieldNode represents the production -// -// EmbeddedField = [ "*" ] TypeName [ TypeArgs ] . -type EmbeddedFieldNode struct { - MUL Token - TypeName *TypeNameNode - TypeArgs *TypeArgsNode -} - -// Source implements Node. -func (n *EmbeddedFieldNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *EmbeddedFieldNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) embeddedField() *EmbeddedFieldNode { - var ( - mulTok Token - typeName *TypeNameNode - typeArgs *TypeArgsNode - ) - // ebnf.Sequence [ "*" ] TypeName [ TypeArgs ] ctx [IDENT, MUL] - { - ix := p.ix - // *ebnf.Option [ "*" ] ctx [IDENT, MUL] - switch p.c() { - case MUL: - // *ebnf.Token "*" ctx [MUL] - mulTok = p.expect(MUL) - } - // *ebnf.Name TypeName ctx [] - switch p.c() { - case IDENT: - if typeName = p.typeName(); typeName == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Option [ TypeArgs ] ctx [] - switch p.c() { - case LBRACK: - // *ebnf.Name TypeArgs ctx [LBRACK] - if typeArgs = p.typeArgs(); typeArgs == nil { - goto _2 - } - } - goto _3 - _2: - typeArgs = nil - _3: - } - return &EmbeddedFieldNode{ - MUL: mulTok, - TypeName: typeName, - TypeArgs: typeArgs, - } -} - -// EmptyStmtNode represents the production -// -// EmptyStmt = . -type EmptyStmtNode struct { -} - -// Source implements Node. -func (n *EmptyStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *EmptyStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) emptyStmt() *EmptyStmtNode { - return &EmptyStmtNode{} -} - -// ExprCaseClauseListNode represents the production -// -// ExprCaseClause = ExprSwitchCase ":" StatementList . -type ExprCaseClauseListNode struct { - ExprSwitchCase Node - COLON Token - StatementList *StatementListNode - List *ExprCaseClauseListNode -} - -// Source implements Node. -func (n *ExprCaseClauseListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ExprCaseClauseListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.ExprSwitchCase.Position() -} - -func (p *parser) exprCaseClause() *ExprCaseClauseListNode { - var ( - ok bool - exprSwitchCase Node - colonTok Token - statementList *StatementListNode - ) - // ebnf.Sequence ExprSwitchCase ":" StatementList ctx [CASE, DEFAULT] - { - p.openScope() - - defer p.closeScope() - - ix := p.ix - // *ebnf.Name ExprSwitchCase ctx [CASE, DEFAULT] - if exprSwitchCase = p.exprSwitchCase(); exprSwitchCase == nil { - p.back(ix) - return nil - } - // *ebnf.Token ":" ctx [] - if colonTok, ok = p.accept(COLON); !ok { - p.back(ix) - return nil - } - // *ebnf.Name StatementList ctx [] - switch p.c() { - case ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, SEMICOLON, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */ : - if statementList = p.statementList(); statementList == nil { - p.back(ix) - return nil - } - } - } - return &ExprCaseClauseListNode{ - ExprSwitchCase: exprSwitchCase, - COLON: colonTok, - StatementList: statementList, - } -} - -// ExprSwitchCaseNode represents the production -// -// ExprSwitchCase = "case" ExpressionList | "default" . -type ExprSwitchCaseNode struct { - CASE Token - Expression Expression - DEFAULT Token -} - -// Source implements Node. -func (n *ExprSwitchCaseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ExprSwitchCaseNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.CASE.Position() -} - -// ExprSwitchCase2Node represents the production -// -// ExprSwitchCase = "case" ExpressionList | "default" . -type ExprSwitchCase2Node struct { - CASE Token - ExpressionList *ExpressionListNode - DEFAULT Token -} - -// Source implements Node. -func (n *ExprSwitchCase2Node) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ExprSwitchCase2Node) Position() (r token.Position) { - if n == nil { - return r - } - - return n.CASE.Position() -} - -func (p *parser) exprSwitchCase() Node { - var ( - caseTok Token - expressionList *ExpressionListNode - defaultTok Token - ) - // ebnf.Alternative "case" ExpressionList | "default" ctx [CASE, DEFAULT] - switch p.c() { - case CASE: // 0 - // ebnf.Sequence "case" ExpressionList ctx [CASE] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _0 - } - ix := p.ix - // *ebnf.Token "case" ctx [CASE] - caseTok = p.expect(CASE) - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _0 - } - } - break - _0: - caseTok = Token{} - expressionList = nil - return nil - case DEFAULT: // 1 - // *ebnf.Token "default" ctx [DEFAULT] - defaultTok = p.expect(DEFAULT) - default: - return nil - } - if expressionList.Len() == 1 { - return &ExprSwitchCaseNode{ - CASE: caseTok, - Expression: expressionList.first(), - DEFAULT: defaultTok, - } - } - - return &ExprSwitchCase2Node{ - CASE: caseTok, - ExpressionList: expressionList, - DEFAULT: defaultTok, - } -} - -// ExprSwitchStmtNode represents the production -// -// ExprSwitchStmt = "switch" [ Expression ] "{" { ExprCaseClause } "}" | "switch" SimpleStmt ";" [ Expression ] "{" { ExprCaseClause } "}" . -type ExprSwitchStmtNode struct { - SWITCH Token - Expression Expression - LBRACE Token - ExprCaseClauseList *ExprCaseClauseListNode - RBRACE Token - SimpleStmt Node - SEMICOLON Token -} - -// Source implements Node. -func (n *ExprSwitchStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ExprSwitchStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) exprSwitchStmt() *ExprSwitchStmtNode { - var ( - ok bool - switchTok Token - expression Expression - lbraceTok Token - list *ExprCaseClauseListNode - rbraceTok Token - simpleStmt Node - semicolonTok Token - ) - // ebnf.Alternative "switch" [ Expression ] "{" { ExprCaseClause } "}" | "switch" SimpleStmt ";" [ Expression ] "{" { ExprCaseClause } "}" ctx [SWITCH] - switch p.c() { - case SWITCH: // 0 1 - // ebnf.Sequence "switch" [ Expression ] "{" { ExprCaseClause } "}" ctx [SWITCH] - { - ix := p.ix - // *ebnf.Token "switch" ctx [SWITCH] - switchTok = p.expect(SWITCH) - // *ebnf.Option [ Expression ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(true); expression == nil { - goto _1 - } - } - goto _2 - _1: - expression = nil - _2: - // *ebnf.Token "{" ctx [] - if lbraceTok, ok = p.accept(LBRACE); !ok { - p.back(ix) - goto _0 - } - // *ebnf.Repetition { ExprCaseClause } ctx [] - var item *ExprCaseClauseListNode - _3: - { - var exprCaseClause *ExprCaseClauseListNode - switch p.c() { - case CASE, DEFAULT: - // *ebnf.Name ExprCaseClause ctx [CASE, DEFAULT] - if exprCaseClause = p.exprCaseClause(); exprCaseClause == nil { - goto _4 - } - if item != nil { - item.List = exprCaseClause - } - item = exprCaseClause - if list == nil { - list = item - } - goto _3 - } - _4: - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - goto _0 - } - } - break - _0: - expression = nil - lbraceTok = Token{} - rbraceTok = Token{} - switchTok = Token{} - // ebnf.Sequence "switch" SimpleStmt ";" [ Expression ] "{" { ExprCaseClause } "}" ctx [SWITCH] - { - ix := p.ix - // *ebnf.Token "switch" ctx [SWITCH] - switchTok = p.expect(SWITCH) - // *ebnf.Name SimpleStmt ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */ : - if simpleStmt = p.simpleStmt(false); simpleStmt == nil { - p.back(ix) - goto _5 - } - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _5 - } - // *ebnf.Option [ Expression ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(true); expression == nil { - goto _6 - } - } - goto _7 - _6: - expression = nil - _7: - // *ebnf.Token "{" ctx [] - if lbraceTok, ok = p.accept(LBRACE); !ok { - p.back(ix) - goto _5 - } - // *ebnf.Repetition { ExprCaseClause } ctx [] - var item *ExprCaseClauseListNode - _8: - { - var exprCaseClause *ExprCaseClauseListNode - switch p.c() { - case CASE, DEFAULT: - // *ebnf.Name ExprCaseClause ctx [CASE, DEFAULT] - if exprCaseClause = p.exprCaseClause(); exprCaseClause == nil { - goto _9 - } - if item != nil { - item.List = exprCaseClause - } - item = exprCaseClause - if list == nil { - list = item - } - goto _8 - } - _9: - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - goto _5 - } - } - break - _5: - expression = nil - lbraceTok = Token{} - rbraceTok = Token{} - semicolonTok = Token{} - simpleStmt = nil - switchTok = Token{} - return nil - default: - return nil - } - return &ExprSwitchStmtNode{ - SWITCH: switchTok, - Expression: expression, - LBRACE: lbraceTok, - ExprCaseClauseList: list, - RBRACE: rbraceTok, - SimpleStmt: simpleStmt, - SEMICOLON: semicolonTok, - } -} - -func (p *parser) expression(preBlock bool) (r Expression) { - var logicalAndExpression Expression - // ebnf.Sequence LogicalAndExpression { "||" LogicalAndExpression } ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name LogicalAndExpression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if logicalAndExpression = p.logicalAndExpression(preBlock); logicalAndExpression == nil { - p.back(ix) - return nil - } - r = logicalAndExpression - // *ebnf.Repetition { "||" LogicalAndExpression } ctx [] - _0: - { - var lorTok Token - var logicalAndExpression Expression - switch p.c() { - case LOR: - // ebnf.Sequence "||" LogicalAndExpression ctx [LOR] - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "||" ctx [LOR] - lorTok = p.expect(LOR) - // *ebnf.Name LogicalAndExpression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if logicalAndExpression = p.logicalAndExpression(preBlock); logicalAndExpression == nil { - p.back(ix) - goto _1 - } - r = &BinaryExpressionNode{LHS: r, Op: lorTok, RHS: logicalAndExpression} - goto _0 - } - _1: - } - } - return r -} - -// ExpressionListNode represents the production -// -// ExpressionList = Expression { "," Expression } . -type ExpressionListNode struct { - COMMA Token - Expression Expression - List *ExpressionListNode -} - -func (n *ExpressionListNode) first() Expression { - if n == nil { - return nil - } - - return n.Expression -} - -// Len reports the number of items in n. -func (n *ExpressionListNode) Len() (r int) { - for ; n != nil; n = n.List { - r++ - } - return r -} - -// Source implements Node. -func (n *ExpressionListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ExpressionListNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.COMMA.IsValid() { - return n.COMMA.Position() - } - - return n.Expression.Position() -} - -func (p *parser) expressionList(preBlock bool) *ExpressionListNode { - var ( - expression Expression - expressionList, last *ExpressionListNode - ) - // ebnf.Sequence Expression { "," Expression } ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(preBlock); expression == nil { - p.back(ix) - return nil - } - expressionList = &ExpressionListNode{ - Expression: expression, - } - last = expressionList - // *ebnf.Repetition { "," Expression } ctx [] - _0: - { - var commaTok Token - switch p.c() { - case COMMA: - // ebnf.Sequence "," Expression ctx [COMMA] - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(preBlock); expression == nil { - p.back(ix) - goto _1 - } - next := &ExpressionListNode{ - COMMA: commaTok, - Expression: expression, - } - last.List = next - last = next - goto _0 - } - _1: - } - } - return expressionList -} - -// FallthroughStmtNode represents the production -// -// FallthroughStmt = "fallthrough" . -type FallthroughStmtNode struct { - FALLTHROUGH Token -} - -// Source implements Node. -func (n *FallthroughStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FallthroughStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) fallthroughStmt() *FallthroughStmtNode { - var ( - fallthroughTok Token - ) - // *ebnf.Token "fallthrough" ctx [FALLTHROUGH] - fallthroughTok = p.expect(FALLTHROUGH) - return &FallthroughStmtNode{ - FALLTHROUGH: fallthroughTok, - } -} - -// FieldDeclNode represents the production -// -// FieldDecl = ( IdentifierList Type | EmbeddedField ) [ Tag ] . -type FieldDeclNode struct { - IdentifierList *IdentifierListNode - TypeNode Type - EmbeddedField *EmbeddedFieldNode - Tag *TagNode -} - -// Source implements Node. -func (n *FieldDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FieldDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.IdentifierList != nil { - return n.IdentifierList.Position() - } - - return n.EmbeddedField.Position() -} - -func (p *parser) fieldDecl() *FieldDeclNode { - var ( - identifierList *IdentifierListNode - typeNode Type - embeddedField *EmbeddedFieldNode - tag *TagNode - ) - // ebnf.Sequence ( IdentifierList Type | EmbeddedField ) [ Tag ] ctx [IDENT, MUL] - { - ix := p.ix - // *ebnf.Group ( IdentifierList Type | EmbeddedField ) ctx [IDENT, MUL] - // ebnf.Alternative IdentifierList Type | EmbeddedField ctx [IDENT, MUL] - switch p.c() { - case IDENT: // 0 1 - // ebnf.Sequence IdentifierList Type ctx [IDENT] - { - ix := p.ix - // *ebnf.Name IdentifierList ctx [IDENT] - if identifierList = p.identifierList(); identifierList == nil { - p.back(ix) - goto _0 - } - // *ebnf.Name Type ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _0 - } - default: - p.back(ix) - goto _0 - } - } - break - _0: - identifierList = nil - typeNode = nil - // *ebnf.Name EmbeddedField ctx [IDENT] - if embeddedField = p.embeddedField(); embeddedField == nil { - goto _1 - } - break - _1: - embeddedField = nil - p.back(ix) - return nil - case MUL: // 1 - // *ebnf.Name EmbeddedField ctx [MUL] - if embeddedField = p.embeddedField(); embeddedField == nil { - goto _2 - } - break - _2: - embeddedField = nil - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - // *ebnf.Option [ Tag ] ctx [] - switch p.c() { - case STRING: - // *ebnf.Name Tag ctx [STRING] - if tag = p.tag(); tag == nil { - goto _4 - } - } - goto _5 - _4: - tag = nil - _5: - } - return &FieldDeclNode{ - IdentifierList: identifierList, - TypeNode: typeNode, - EmbeddedField: embeddedField, - Tag: tag, - } -} - -// ForClauseNode represents the production -// -// ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . -type ForClauseNode struct { - InitStmt Node - SEMICOLON Token - Condition Expression - SEMICOLON2 Token - PostStmt Node -} - -// Source implements Node. -func (n *ForClauseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ForClauseNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) forClause() *ForClauseNode { - var ( - ok bool - initStmt Node - semicolonTok Token - condition Expression - semicolon2Tok Token - postStmt Node - ) - // ebnf.Sequence [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, SEMICOLON, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Option [ InitStmt ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, SEMICOLON, STRING, STRUCT, SUB, XOR] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name InitStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if initStmt = p.initStmt(); initStmt == nil { - goto _0 - } - } - goto _1 - _0: - initStmt = nil - _1: - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - return nil - } - // *ebnf.Option [ Condition ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name Condition ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if condition = p.condition(false); condition == nil { - goto _2 - } - } - goto _3 - _2: - condition = nil - _3: - // *ebnf.Token ";" ctx [] - if semicolon2Tok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - return nil - } - // *ebnf.Option [ PostStmt ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */ : - // *ebnf.Name PostStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */] - if postStmt = p.postStmt(); postStmt == nil { - goto _4 - } - } - goto _5 - _4: - postStmt = nil - _5: - } - return &ForClauseNode{ - InitStmt: initStmt, - SEMICOLON: semicolonTok, - Condition: condition, - SEMICOLON2: semicolon2Tok, - PostStmt: postStmt, - } -} - -// ForStmtNode represents the production -// -// ForStmt = "for" [ ForClause | RangeClause | Condition ] Block . -type ForStmtNode struct { - FOR Token - ForClause *ForClauseNode - RangeClause *RangeClauseNode - Condition Expression - Block *BlockNode -} - -// Source implements Node. -func (n *ForStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ForStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.FOR.Position() -} - -func (p *parser) forStmt() *ForStmtNode { - var ( - forTok Token - forClause *ForClauseNode - rangeClause *RangeClauseNode - condition Expression - block *BlockNode - ) - // ebnf.Sequence "for" [ ForClause | RangeClause | Condition ] Block ctx [FOR] - { - p.openScope() - - defer p.closeScope() - - ix := p.ix - // *ebnf.Token "for" ctx [FOR] - forTok = p.expect(FOR) - // *ebnf.Option [ ForClause | RangeClause | Condition ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, RANGE, SEMICOLON, STRING, STRUCT, SUB, XOR: - // ebnf.Alternative ForClause | RangeClause | Condition ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, RANGE, SEMICOLON, STRING, STRUCT, SUB, XOR] - switch p.c() { - case SEMICOLON: // 0 - // *ebnf.Name ForClause ctx [SEMICOLON] - if forClause = p.forClause(); forClause == nil { - goto _2 - } - break - _2: - forClause = nil - goto _0 - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: // 0 1 2 - // *ebnf.Name ForClause ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if forClause = p.forClause(); forClause == nil { - goto _4 - } - break - _4: - forClause = nil - // *ebnf.Name RangeClause ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if rangeClause = p.rangeClause(); rangeClause == nil { - goto _5 - } - break - _5: - rangeClause = nil - // *ebnf.Name Condition ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if condition = p.condition(true); condition == nil { - goto _6 - } - break - _6: - condition = nil - goto _0 - case RANGE: // 1 - // *ebnf.Name RangeClause ctx [RANGE] - if rangeClause = p.rangeClause(); rangeClause == nil { - goto _7 - } - break - _7: - rangeClause = nil - goto _0 - default: - goto _0 - } - } - goto _1 - _0: - forClause = nil - rangeClause = nil - _1: - // *ebnf.Name Block ctx [] - switch p.c() { - case LBRACE: - if block = p.block(nil, nil); block == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &ForStmtNode{ - FOR: forTok, - ForClause: forClause, - RangeClause: rangeClause, - Condition: condition, - Block: block, - } -} - -// FunctionBodyNode represents the production -// -// FunctionBody = Block . -type FunctionBodyNode struct { - Block *BlockNode -} - -// Source implements Node. -func (n *FunctionBodyNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FunctionBodyNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Block.Position() -} - -func (p *parser) functionBody(rx *ParametersNode, s *SignatureNode) *FunctionBodyNode { - var ( - block *BlockNode - ) - // *ebnf.Name Block ctx [LBRACE] - if block = p.block(rx, s); block == nil { - return nil - } - return &FunctionBodyNode{ - Block: block, - } -} - -// FunctionDeclNode represents the production -// -// FunctionDecl = "func" FunctionName [ TypeParameters ] Signature [ FunctionBody ] . -type FunctionDeclNode struct { - FUNC Token - FunctionName *FunctionNameNode - TypeParameters *TypeParametersNode - Signature *SignatureNode - FunctionBody *FunctionBodyNode - - visible -} - -// Source implements Node. -func (n *FunctionDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FunctionDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.FUNC.Position() -} - -func (p *parser) functionDecl() (r *FunctionDeclNode) { - var ( - funcTok Token - functionName *FunctionNameNode - typeParameters *TypeParametersNode - signature *SignatureNode - functionBody *FunctionBodyNode - ) - // ebnf.Sequence "func" FunctionName [ TypeParameters ] Signature [ FunctionBody ] ctx [FUNC] - { - if p.peek(1) != IDENT { - return nil - } - ix := p.ix - // *ebnf.Token "func" ctx [FUNC] - funcTok = p.expect(FUNC) - // *ebnf.Name FunctionName ctx [IDENT] - if functionName = p.functionName(); functionName == nil { - p.back(ix) - return nil - } - // *ebnf.Option [ TypeParameters ] ctx [] - switch p.c() { - case LBRACK: - // *ebnf.Name TypeParameters ctx [LBRACK] - if typeParameters = p.typeParameters(); typeParameters == nil { - goto _0 - } - } - goto _1 - _0: - typeParameters = nil - _1: - // *ebnf.Name Signature ctx [] - switch p.c() { - case LPAREN: - if signature = p.signature(); signature == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Option [ FunctionBody ] ctx [] - switch p.c() { - case LBRACE: - // *ebnf.Name FunctionBody ctx [LBRACE] - if functionBody = p.functionBody(nil, signature); functionBody == nil { - goto _2 - } - } - goto _3 - _2: - functionBody = nil - _3: - } - sc := p.sc - r = &FunctionDeclNode{ - FUNC: funcTok, - FunctionName: functionName, - TypeParameters: typeParameters, - Signature: signature, - FunctionBody: functionBody, - } - p.declare(sc, functionName.IDENT, r, 0, true) - return r -} - -// FunctionLitNode represents the production -// -// FunctionLit = "func" Signature FunctionBody . -type FunctionLitNode struct { - FUNC Token - Signature *SignatureNode - FunctionBody *FunctionBodyNode -} - -// Source implements Node. -func (n *FunctionLitNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FunctionLitNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.FUNC.Position() -} - -func (p *parser) functionLit() *FunctionLitNode { - var ( - funcTok Token - signature *SignatureNode - functionBody *FunctionBodyNode - ) - // ebnf.Sequence "func" Signature FunctionBody ctx [FUNC] - { - switch p.peek(1) { - case LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Token "func" ctx [FUNC] - funcTok = p.expect(FUNC) - // *ebnf.Name Signature ctx [LPAREN] - if signature = p.signature(); signature == nil { - p.back(ix) - return nil - } - // *ebnf.Name FunctionBody ctx [] - switch p.c() { - case LBRACE: - if functionBody = p.functionBody(nil, signature); functionBody == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &FunctionLitNode{ - FUNC: funcTok, - Signature: signature, - FunctionBody: functionBody, - } -} - -// FunctionNameNode represents the production -// -// FunctionName = identifier . -type FunctionNameNode struct { - IDENT Token -} - -// Source implements Node. -func (n *FunctionNameNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FunctionNameNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IDENT.Position() -} - -func (p *parser) functionName() *FunctionNameNode { - var ( - identTok Token - ) - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - return &FunctionNameNode{ - IDENT: identTok, - } -} - -// FunctionTypeNode represents the production -// -// FunctionType = "func" Signature . -type FunctionTypeNode struct { - FUNC Token - Signature *SignatureNode - - guard -} - -// Source implements Node. -func (n *FunctionTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FunctionTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.FUNC.Position() -} - -func (p *parser) functionType() *FunctionTypeNode { - var ( - funcTok Token - signature *SignatureNode - ) - // ebnf.Sequence "func" Signature ctx [FUNC] - { - switch p.peek(1) { - case LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Token "func" ctx [FUNC] - funcTok = p.expect(FUNC) - // *ebnf.Name Signature ctx [LPAREN] - if signature = p.signature(); signature == nil { - p.back(ix) - return nil - } - } - return &FunctionTypeNode{ - FUNC: funcTok, - Signature: signature, - } -} - -// GoStmtNode represents the production -// -// GoStmt = "go" Expression . -type GoStmtNode struct { - GO Token - Expression Expression -} - -// Source implements Node. -func (n *GoStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *GoStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.GO.Position() -} - -func (p *parser) goStmt() *GoStmtNode { - var ( - goTok Token - expression Expression - ) - // ebnf.Sequence "go" Expression ctx [GO] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - return nil - } - ix := p.ix - // *ebnf.Token "go" ctx [GO] - goTok = p.expect(GO) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression == nil { - p.back(ix) - return nil - } - } - return &GoStmtNode{ - GO: goTok, - Expression: expression, - } -} - -// GotoStmtNode represents the production -// -// GotoStmt = "goto" Label . -type GotoStmtNode struct { - GOTO Token - Label *LabelNode -} - -// Source implements Node. -func (n *GotoStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *GotoStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.GOTO.Position() -} - -func (p *parser) gotoStmt() *GotoStmtNode { - var ( - gotoTok Token - label *LabelNode - ) - // ebnf.Sequence "goto" Label ctx [GOTO] - { - if p.peek(1) != IDENT { - return nil - } - ix := p.ix - // *ebnf.Token "goto" ctx [GOTO] - gotoTok = p.expect(GOTO) - // *ebnf.Name Label ctx [IDENT] - if label = p.label(); label == nil { - p.back(ix) - return nil - } - } - return &GotoStmtNode{ - GOTO: gotoTok, - Label: label, - } -} - -// IdentifierListNode represents the production -// -// IdentifierList = identifier { "," identifier } . -type IdentifierListNode struct { - COMMA Token - IDENT Token - List *IdentifierListNode -} - -// Len reports the number of items in n. -func (n *IdentifierListNode) Len() (r int) { - for ; n != nil; n = n.List { - r++ - } - return r -} - -func (n *IdentifierListNode) first() (r Token) { - if n != nil { - r = n.IDENT - } - return r -} - -// Source implements Node. -func (n *IdentifierListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *IdentifierListNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.COMMA.IsValid() { - return n.COMMA.Position() - } - - return n.IDENT.Position() -} - -func (p *parser) identifierList() *IdentifierListNode { - var ( - identTok Token - list, last *IdentifierListNode - ) - // ebnf.Sequence identifier { "," identifier } ctx [IDENT] - { - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - // *ebnf.Repetition { "," identifier } ctx [] - list = &IdentifierListNode{ - IDENT: identTok, - } - last = list - _0: - { - var commaTok Token - var identTok Token - switch p.c() { - case COMMA: - // ebnf.Sequence "," identifier ctx [COMMA] - if p.peek(1) != IDENT { - goto _1 - } - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - next := &IdentifierListNode{ - COMMA: commaTok, - IDENT: identTok, - } - last.List = next - last = next - goto _0 - } - _1: - } - } - return list -} - -// IfElseStmtNode represents the production -// -// IfStmt = "if" Expression Block [ "else" ( IfStmt | Block ) ] | "if" SimpleStmt ";" Expression Block [ "else" ( IfStmt | Block ) ] . -type IfElseStmtNode struct { - IF Token - Expression Expression - Block *BlockNode - ELSE Token - ElseClause Node - SimpleStmt Node - SEMICOLON Token -} - -// Source implements Node. -func (n *IfElseStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *IfElseStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -// IfStmtNode represents the production -// -// IfStmt = "if" Expression Block [ "else" ( IfStmt | Block ) ] | "if" SimpleStmt ";" Expression Block [ "else" ( IfStmt | Block ) ] . -type IfStmtNode struct { - IF Token - Expression Expression - Block *BlockNode - SimpleStmt Node - SEMICOLON Token -} - -// Source implements Node. -func (n *IfStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *IfStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) ifStmt() Node { - var ( - ok bool - ifTok Token - expression Expression - block *BlockNode - elseTok Token - ifStmt Node - block2 *BlockNode - simpleStmt Node - semicolonTok Token - ) - // ebnf.Alternative "if" Expression Block [ "else" ( IfStmt | Block ) ] | "if" SimpleStmt ";" Expression Block [ "else" ( IfStmt | Block ) ] ctx [IF] - switch p.c() { - case IF: // 0 1 - p.openScope() - - defer p.closeScope() - - // ebnf.Sequence "if" Expression Block [ "else" ( IfStmt | Block ) ] ctx [IF] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _0 - } - ix := p.ix - // *ebnf.Token "if" ctx [IF] - ifTok = p.expect(IF) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(true); expression == nil { - p.back(ix) - goto _0 - } - // *ebnf.Name Block ctx [] - switch p.c() { - case LBRACE: - if block = p.block(nil, nil); block == nil { - p.back(ix) - goto _0 - } - default: - p.back(ix) - goto _0 - } - // *ebnf.Option [ "else" ( IfStmt | Block ) ] ctx [] - switch p.c() { - case ELSE: - // ebnf.Sequence "else" ( IfStmt | Block ) ctx [ELSE] - { - switch p.peek(1) { - case IF, LBRACE: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "else" ctx [ELSE] - elseTok = p.expect(ELSE) - // *ebnf.Group ( IfStmt | Block ) ctx [IF, LBRACE] - // ebnf.Alternative IfStmt | Block ctx [IF, LBRACE] - switch p.c() { - case IF: // 0 - // *ebnf.Name IfStmt ctx [IF] - if ifStmt = p.ifStmt(); ifStmt == nil { - goto _3 - } - break - _3: - ifStmt = nil - p.back(ix) - goto _1 - case LBRACE: // 1 - // *ebnf.Name Block ctx [LBRACE] - if block2 = p.block(nil, nil); block2 == nil { - goto _5 - } - break - _5: - block2 = nil - p.back(ix) - goto _1 - default: - p.back(ix) - goto _1 - } - } - default: - return &IfStmtNode{ - IF: ifTok, - Expression: expression, - Block: block, - SimpleStmt: simpleStmt, - SEMICOLON: semicolonTok, - } - } - goto _2 - _1: - block2 = nil - elseTok = Token{} - ifStmt = nil - _2: - } - break - _0: - block = nil - block2 = nil - elseTok = Token{} - expression = nil - ifStmt = nil - ifTok = Token{} - // ebnf.Sequence "if" SimpleStmt ";" Expression Block [ "else" ( IfStmt | Block ) ] ctx [IF] - { - ix := p.ix - // *ebnf.Token "if" ctx [IF] - ifTok = p.expect(IF) - // *ebnf.Name SimpleStmt ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */ : - if simpleStmt = p.simpleStmt(false); simpleStmt == nil { - p.back(ix) - goto _7 - } - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _7 - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression = p.expression(true); expression == nil { - p.back(ix) - goto _7 - } - default: - p.back(ix) - goto _7 - } - // *ebnf.Name Block ctx [] - switch p.c() { - case LBRACE: - if block = p.block(nil, nil); block == nil { - p.back(ix) - goto _7 - } - default: - p.back(ix) - goto _7 - } - // *ebnf.Option [ "else" ( IfStmt | Block ) ] ctx [] - switch p.c() { - case ELSE: - // ebnf.Sequence "else" ( IfStmt | Block ) ctx [ELSE] - { - switch p.peek(1) { - case IF, LBRACE: - default: - goto _8 - } - ix := p.ix - // *ebnf.Token "else" ctx [ELSE] - elseTok = p.expect(ELSE) - // *ebnf.Group ( IfStmt | Block ) ctx [IF, LBRACE] - // ebnf.Alternative IfStmt | Block ctx [IF, LBRACE] - switch p.c() { - case IF: // 0 - // *ebnf.Name IfStmt ctx [IF] - if ifStmt = p.ifStmt(); ifStmt == nil { - goto _10 - } - break - _10: - ifStmt = nil - p.back(ix) - goto _8 - case LBRACE: // 1 - // *ebnf.Name Block ctx [LBRACE] - if block2 = p.block(nil, nil); block2 == nil { - goto _12 - } - break - _12: - block2 = nil - p.back(ix) - goto _8 - default: - p.back(ix) - goto _8 - } - } - } - goto _9 - _8: - block2 = nil - elseTok = Token{} - ifStmt = nil - _9: - } - break - _7: - block = nil - block2 = nil - elseTok = Token{} - expression = nil - ifStmt = nil - ifTok = Token{} - semicolonTok = Token{} - simpleStmt = nil - return nil - default: - return nil - } - var elseClause Node - switch { - case ifStmt != nil: - elseClause = ifStmt - case block2 != nil: - elseClause = block2 - } - return &IfElseStmtNode{ - IF: ifTok, - Expression: expression, - Block: block, - ELSE: elseTok, - ElseClause: elseClause, - SimpleStmt: simpleStmt, - SEMICOLON: semicolonTok, - } -} - -// ImportSpecListNode represents the production -// -// ImportSpecListNode = { ImportSpec ";" } . -type ImportSpecListNode struct { - ImportSpec *ImportSpecNode - SEMICOLON Token - List *ImportSpecListNode -} - -// Source implements Node. -func (n *ImportSpecListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ImportSpecListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.ImportSpec.Position() -} - -// ImportDeclNode represents the production -// -// ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) . -type ImportDeclNode struct { - IMPORT Token - LPAREN Token - ImportSpecList *ImportSpecListNode - RPAREN Token -} - -// Source implements Node. -func (n *ImportDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ImportDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IMPORT.Position() -} - -func (p *parser) importDecl() *ImportDeclNode { - var ( - ok bool - importTok Token - importSpec *ImportSpecNode - lparenTok Token - list, last *ImportSpecListNode - rparenTok Token - ) - // ebnf.Sequence "import" ( ImportSpec | "(" { ImportSpec ";" } [ ImportSpec ] ")" ) ctx [IMPORT] - { - switch p.peek(1) { - case IDENT, LPAREN, PERIOD, STRING: - default: - return nil - } - ix := p.ix - // *ebnf.Token "import" ctx [IMPORT] - importTok = p.expect(IMPORT) - // *ebnf.Group ( ImportSpec | "(" { ImportSpec ";" } [ ImportSpec ] ")" ) ctx [IDENT, LPAREN, PERIOD, STRING] - // ebnf.Alternative ImportSpec | "(" { ImportSpec ";" } [ ImportSpec ] ")" ctx [IDENT, LPAREN, PERIOD, STRING] - switch p.c() { - case IDENT, PERIOD, STRING: // 0 - // *ebnf.Name ImportSpec ctx [IDENT, PERIOD, STRING] - if importSpec = p.importSpec(); importSpec == nil { - goto _0 - } - list = &ImportSpecListNode{ - ImportSpec: importSpec, - } - break - _0: - importSpec = nil - p.back(ix) - return nil - case LPAREN: // 1 - // ebnf.Sequence "(" { ImportSpec ";" } [ ImportSpec ] ")" ctx [LPAREN] - { - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Repetition { ImportSpec ";" } ctx [] - _4: - { - var importSpec *ImportSpecNode - var semicolonTok Token - switch p.c() { - case IDENT, PERIOD, STRING: - // ebnf.Sequence ImportSpec ";" ctx [IDENT, PERIOD, STRING] - ix := p.ix - // *ebnf.Name ImportSpec ctx [IDENT, PERIOD, STRING] - if importSpec = p.importSpec(); importSpec == nil { - p.back(ix) - goto _5 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - next := &ImportSpecListNode{ - ImportSpec: importSpec, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _5 - } - next := &ImportSpecListNode{ - ImportSpec: importSpec, - SEMICOLON: semicolonTok, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _4 - } - _5: - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - goto _2 - } - } - break - _2: - lparenTok = Token{} - rparenTok = Token{} - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - } - return &ImportDeclNode{ - IMPORT: importTok, - LPAREN: lparenTok, - ImportSpecList: list, - RPAREN: rparenTok, - } -} - -// ImportSpecNode represents the production -// -// ImportSpec = [ "." | PackageName ] ImportPath . -type ImportSpecNode struct { - PERIOD Token - PackageName Token - ImportPath *BasicLitNode - - pkg *Package - visible -} - -// Source implements Node. -func (n *ImportSpecNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ImportSpecNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.PERIOD.IsValid() { - return n.PERIOD.Position() - } - - if n.PackageName.IsValid() { - return n.PackageName.Position() - } - - return n.ImportPath.Position() -} - -func (p *parser) importSpec() *ImportSpecNode { - var ( - periodTok Token - packageName Token - importPath *BasicLitNode - ) - // ebnf.Sequence [ "." | PackageName ] ImportPath ctx [IDENT, PERIOD, STRING] - { - ix := p.ix - // *ebnf.Option [ "." | PackageName ] ctx [IDENT, PERIOD, STRING] - switch p.c() { - case IDENT, PERIOD: - // ebnf.Alternative "." | PackageName ctx [IDENT, PERIOD] - switch p.c() { - case PERIOD: // 0 - // *ebnf.Token "." ctx [PERIOD] - periodTok = p.expect(PERIOD) - case IDENT: // 1 - // *ebnf.Name PackageName ctx [IDENT] - if packageName = p.packageName(); !packageName.IsValid() { - goto _4 - } - break - _4: - packageName = Token{} - goto _0 - default: - goto _0 - } - } - goto _1 - _0: - packageName = Token{} - periodTok = Token{} - _1: - // *ebnf.Name ImportPath ctx [] - switch p.c() { - case STRING: - if importPath = p.basicLit().(*BasicLitNode); importPath == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &ImportSpecNode{ - PERIOD: periodTok, - PackageName: packageName, - ImportPath: importPath, - } -} - -// IndexNode represents the production -// -// Index = "[" Expression "]" . -type IndexNode struct { - LBRACK Token - Expression Expression - RBRACK Token -} - -// Source implements Node. -func (n *IndexNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *IndexNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACK.Position() -} - -func (p *parser) index() *IndexNode { - var ( - ok bool - lbrackTok Token - expression Expression - rbrackTok Token - ) - // ebnf.Sequence "[" Expression "]" ctx [LBRACK] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - return nil - } - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression == nil { - p.back(ix) - return nil - } - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - return nil - } - } - return &IndexNode{ - LBRACK: lbrackTok, - Expression: expression, - RBRACK: rbrackTok, - } -} -func (p *parser) initStmt() Node { - // *ebnf.Name SimpleStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */] - return p.simpleStmt(true) -} - -// InterfaceElemNode represents the production -// -// InterfaceElem = MethodElem | TypeElem . -type InterfaceElemNode struct { - MethodElem *MethodElemNode - TypeElem *TypeElemListNode -} - -// Source implements Node. -func (n *InterfaceElemNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *InterfaceElemNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.MethodElem != nil { - return n.MethodElem.Position() - } - - return n.TypeElem.Position() -} - -func (p *parser) interfaceElem() *InterfaceElemNode { - var ( - methodElem *MethodElemNode - typeElem *TypeElemListNode - ) - // ebnf.Alternative MethodElem | TypeElem ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - switch p.c() { - case IDENT: // 0 1 - // *ebnf.Name MethodElem ctx [IDENT] - if methodElem = p.methodElem(); methodElem == nil { - goto _0 - } - break - _0: - methodElem = nil - // *ebnf.Name TypeElem ctx [IDENT] - if typeElem = p.typeElem(); typeElem == nil { - goto _1 - } - break - _1: - typeElem = nil - return nil - case ARROW, CHAN, FUNC, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE: // 1 - // *ebnf.Name TypeElem ctx [ARROW, CHAN, FUNC, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - if typeElem = p.typeElem(); typeElem == nil { - goto _2 - } - break - _2: - typeElem = nil - return nil - default: - return nil - } - return &InterfaceElemNode{ - MethodElem: methodElem, - TypeElem: typeElem, - } -} - -// InterfaceElemListNode represents the production -// -// InterfaceElemListNode = { InterfaceElem ";" } . -type InterfaceElemListNode struct { - InterfaceElem *InterfaceElemNode - SEMICOLON Token - List *InterfaceElemListNode -} - -// Source implements Node. -func (n *InterfaceElemListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *InterfaceElemListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.InterfaceElem.Position() -} - -// InterfaceTypeNode represents the production -// -// InterfaceType = "interface" "{" { InterfaceElem ";" } "}" . -type InterfaceTypeNode struct { - INTERFACE Token - LBRACE Token - InterfaceElemList *InterfaceElemListNode - RBRACE Token - - guard - - methods map[string]*MethodElemNode -} - -// Source implements Node. -func (n *InterfaceTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *InterfaceTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.INTERFACE.Position() -} - -func (p *parser) interfaceType() *InterfaceTypeNode { - var ( - ok bool - interfaceTok Token - lbraceTok Token - list, last *InterfaceElemListNode - rbraceTok Token - ) - // ebnf.Sequence "interface" "{" { InterfaceElem ";" } [ InterfaceElem ] "}" ctx [INTERFACE] - { - if p.peek(1) != LBRACE { - return nil - } - ix := p.ix - // *ebnf.Token "interface" ctx [INTERFACE] - interfaceTok = p.expect(INTERFACE) - // *ebnf.Token "{" ctx [LBRACE] - lbraceTok = p.expect(LBRACE) - // *ebnf.Repetition { InterfaceElem ";" } ctx [] - _0: - { - var interfaceElem *InterfaceElemNode - var semicolonTok Token - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE: - // ebnf.Sequence InterfaceElem ";" ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - ix := p.ix - // *ebnf.Name InterfaceElem ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - if interfaceElem = p.interfaceElem(); interfaceElem == nil { - p.back(ix) - goto _1 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - next := &InterfaceElemListNode{ - InterfaceElem: interfaceElem, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _1 - } - next := &InterfaceElemListNode{ - InterfaceElem: interfaceElem, - SEMICOLON: semicolonTok, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _0 - } - _1: - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - return nil - } - } - return &InterfaceTypeNode{ - INTERFACE: interfaceTok, - LBRACE: lbraceTok, - InterfaceElemList: list, - RBRACE: rbraceTok, - } -} - -// KeyedElementNode represents the production -// -// KeyedElement = Element [ ":" Element ] . -type KeyedElementNode struct { - Element Expression - COLON Token - Element2 Expression -} - -// Source implements Node. -func (n *KeyedElementNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *KeyedElementNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Element.Position() -} - -func (p *parser) keyedElement() Expression { - var ( - element Expression - colonTok Token - element2 Expression - ) - // ebnf.Sequence Element [ ":" Element ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name Element ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if element = p.element(); element == nil { - p.back(ix) - return nil - } - // *ebnf.Option [ ":" Element ] ctx [] - switch p.c() { - case COLON: - // ebnf.Sequence ":" Element ctx [COLON] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _0 - } - ix := p.ix - // *ebnf.Token ":" ctx [COLON] - colonTok = p.expect(COLON) - // *ebnf.Name Element ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if element2 = p.element(); element2 == nil { - p.back(ix) - goto _0 - } - } - } - goto _1 - _0: - colonTok = Token{} - element2 = nil - _1: - } - if !colonTok.IsValid() { - return element - } - - return &KeyedElementNode{ - Element: element, - COLON: colonTok, - Element2: element2, - } -} - -// LabelNode represents the production -// -// Label = identifier . -type LabelNode struct { - IDENT Token -} - -// Source implements Node. -func (n *LabelNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *LabelNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IDENT.Position() -} - -func (p *parser) label() *LabelNode { - var ( - identTok Token - ) - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - return &LabelNode{ - IDENT: identTok, - } -} - -// LabeledStmtNode represents the production -// -// LabeledStmt = Label ":" Statement . -type LabeledStmtNode struct { - Label *LabelNode - COLON Token - Statement Node -} - -// Source implements Node. -func (n *LabeledStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *LabeledStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Label.Position() -} - -func (p *parser) labeledStmt() *LabeledStmtNode { - var ( - label *LabelNode - colonTok Token - statement Node - ) - // ebnf.Sequence Label ":" Statement ctx [IDENT] - { - if p.peek(1) != COLON { - return nil - } - ix := p.ix - // *ebnf.Name Label ctx [IDENT] - if label = p.label(); label == nil { - p.back(ix) - return nil - } - // *ebnf.Token ":" ctx [COLON] - colonTok = p.expect(COLON) - // *ebnf.Name Statement ctx [] - switch p.c() { - case ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */ : - if statement = p.statement(); statement == nil { - p.back(ix) - return nil - } - } - } - return &LabeledStmtNode{ - Label: label, - COLON: colonTok, - Statement: statement, - } -} - -func (p *parser) literal() Expression { - var ( - basicLit Expression - compositeLit *CompositeLitNode - functionLit *FunctionLitNode - ) - // ebnf.Alternative BasicLit | CompositeLit | FunctionLit ctx [CHAR, FLOAT, FUNC, IMAG, INT, LBRACK, MAP, STRING, STRUCT] - switch p.c() { - case CHAR, FLOAT, IMAG, INT, STRING: // 0 - // *ebnf.Name BasicLit ctx [CHAR, FLOAT, IMAG, INT, STRING] - if basicLit = p.basicLit(); basicLit == nil { - return nil - } - return basicLit - case LBRACK, MAP, STRUCT: // 1 - // *ebnf.Name CompositeLit ctx [LBRACK, MAP, STRUCT] - if compositeLit = p.compositeLit(); compositeLit == nil { - return nil - } - return compositeLit - case FUNC: // 2 - // *ebnf.Name FunctionLit ctx [FUNC] - if functionLit = p.functionLit(); functionLit == nil { - return nil - } - return functionLit - default: - return nil - } -} - -// ArrayLiteralTypeNode represents the production -// -// ArrayLiteralType = StructType | ArrayType | "[" "..." "]" ElementType | SliceType | MapType . -type ArrayLiteralTypeNode struct { - LBRACK Token - ELLIPSIS Token - RBRACK Token - ElementType Node -} - -// Source implements Node. -func (n *ArrayLiteralTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ArrayLiteralTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACK.Position() -} - -func (p *parser) literalType() Node { - var ( - ok bool - structType *StructTypeNode - arrayType *ArrayTypeNode - lbrackTok Token - ellipsisTok Token - rbrackTok Token - elementType Node - sliceType *SliceTypeNode - mapType *MapTypeNode - ) - // ebnf.Alternative StructType | ArrayType | "[" "..." "]" ElementType | SliceType | MapType ctx [LBRACK, MAP, STRUCT] - switch p.c() { - case STRUCT: // 0 - // *ebnf.Name StructType ctx [STRUCT] - if structType = p.structType(); structType != nil { - return structType - } - case LBRACK: // 1 2 3 - // *ebnf.Name ArrayType ctx [LBRACK] - if arrayType = p.arrayType(); arrayType != nil { - return arrayType - } - - // ebnf.Sequence "[" "..." "]" ElementType ctx [LBRACK] - { - if p.peek(1) != ELLIPSIS { - goto _3 - } - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Token "..." ctx [ELLIPSIS] - ellipsisTok = p.expect(ELLIPSIS) - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - goto _3 - } - // *ebnf.Name ElementType ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if elementType = p.type1(); elementType == nil { - p.back(ix) - goto _3 - } - default: - p.back(ix) - goto _3 - } - } - return &ArrayLiteralTypeNode{ - LBRACK: lbrackTok, - ELLIPSIS: ellipsisTok, - RBRACK: rbrackTok, - ElementType: elementType, - } - _3: - elementType = nil - ellipsisTok = Token{} - lbrackTok = Token{} - rbrackTok = Token{} - // *ebnf.Name SliceType ctx [LBRACK] - if sliceType = p.sliceType(); sliceType != nil { - return sliceType - } - - return nil - case MAP: // 4 - // *ebnf.Name MapType ctx [MAP] - if mapType = p.mapType(); mapType != nil { - return mapType - } - } - return nil -} - -// KeyedElementListNode represents the production -// -// KeyedElementListNode = { KeyedElement "," } . -type KeyedElementListNode struct { - KeyedElement Expression - COMMA Token - List *KeyedElementListNode -} - -// Source implements Node. -func (n *KeyedElementListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *KeyedElementListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.KeyedElement.Position() -} - -// LiteralValueNode represents the production -// -// LiteralValue = "{" { KeyedElement "," } "}" . -type LiteralValueNode struct { - LBRACE Token - KeyedElementList *KeyedElementListNode - RBRACE Token -} - -// Source implements Node. -func (n *LiteralValueNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *LiteralValueNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACE.Position() -} - -func (p *parser) literalValue() *LiteralValueNode { - var ( - ok bool - lbraceTok Token - list, last *KeyedElementListNode - keyedElement Expression - rbraceTok Token - ) - // ebnf.Sequence "{" [ ElementList [ "," ] ] "}" ctx [LBRACE] - ix := p.ix - // *ebnf.Token "{" ctx [LBRACE] - lbraceTok = p.expect(LBRACE) - for { - // *ebnf.Option [ ElementList [ "," ] ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - { - ix := p.ix - if keyedElement = p.keyedElement(); keyedElement == nil { - p.back(ix) - goto _1 - } - switch p.c() { - case COMMA: - // *ebnf.Token "," ctx [COMMA] - next := &KeyedElementListNode{ - KeyedElement: keyedElement, - COMMA: p.consume(), - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - continue - case RBRACE: - next := &KeyedElementListNode{ - KeyedElement: keyedElement, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - } - } - } - goto _1 - } -_1: - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - return nil - } - return &LiteralValueNode{ - LBRACE: lbraceTok, - KeyedElementList: list, - RBRACE: rbraceTok, - } -} - -func (p *parser) logicalAndExpression(preBlock bool) (r Expression) { - var relationalExpression Expression - // ebnf.Sequence RelationalExpression { "&&" RelationalExpression } ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name RelationalExpression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if relationalExpression = p.relationalExpression(preBlock); relationalExpression == nil { - p.back(ix) - return nil - } - r = relationalExpression - // *ebnf.Repetition { "&&" RelationalExpression } ctx [] - _0: - { - var landTok Token - var relationalExpression Expression - switch p.c() { - case LAND: - // ebnf.Sequence "&&" RelationalExpression ctx [LAND] - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "&&" ctx [LAND] - landTok = p.expect(LAND) - // *ebnf.Name RelationalExpression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if relationalExpression = p.relationalExpression(preBlock); relationalExpression == nil { - p.back(ix) - goto _1 - } - r = &BinaryExpressionNode{LHS: r, Op: landTok, RHS: relationalExpression} - goto _0 - } - _1: - } - } - return r -} - -// MapTypeNode represents the production -// -// MapType = "map" "[" KeyType "]" ElementType . -type MapTypeNode struct { - MAP Token - LBRACK Token - KeyType Node - RBRACK Token - ElementType Node -} - -// Source implements Node. -func (n *MapTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *MapTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.MAP.Position() -} - -func (p *parser) mapType() *MapTypeNode { - var ( - ok bool - mapTok Token - lbrackTok Token - keyType Node - rbrackTok Token - elementType Node - ) - // ebnf.Sequence "map" "[" KeyType "]" ElementType ctx [MAP] - { - if p.peek(1) != LBRACK { - return nil - } - ix := p.ix - // *ebnf.Token "map" ctx [MAP] - mapTok = p.expect(MAP) - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Name KeyType ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if keyType = p.type1(); keyType == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - return nil - } - // *ebnf.Name ElementType ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if elementType = p.type1(); elementType == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &MapTypeNode{ - MAP: mapTok, - LBRACK: lbrackTok, - KeyType: keyType, - RBRACK: rbrackTok, - ElementType: elementType, - } -} - -// MethodDeclNode represents the production -// -// MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] . -type MethodDeclNode struct { - FUNC Token - Receiver *ParametersNode - MethodName Token - Signature *SignatureNode - FunctionBody *FunctionBodyNode -} - -// Source implements Node. -func (n *MethodDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *MethodDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.FUNC.Position() -} - -func (p *parser) methodDecl() *MethodDeclNode { - var ( - funcTok Token - receiver *ParametersNode - methodName Token - signature *SignatureNode - functionBody *FunctionBodyNode - ) - // ebnf.Sequence "func" Receiver MethodName Signature [ FunctionBody ] ctx [FUNC] - { - switch p.peek(1) { - case LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Token "func" ctx [FUNC] - funcTok = p.expect(FUNC) - // *ebnf.Name Receiver ctx [LPAREN] - if receiver = p.receiver(); receiver == nil { - p.back(ix) - return nil - } - // *ebnf.Name MethodName ctx [] - switch p.c() { - case IDENT: - if methodName = p.methodName(); !methodName.IsValid() { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Name Signature ctx [] - switch p.c() { - case LPAREN: - if signature = p.signature(); signature == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Option [ FunctionBody ] ctx [] - switch p.c() { - case LBRACE: - // *ebnf.Name FunctionBody ctx [LBRACE] - if functionBody = p.functionBody(receiver, signature); functionBody == nil { - goto _0 - } - } - goto _1 - _0: - functionBody = nil - _1: - } - return &MethodDeclNode{ - FUNC: funcTok, - Receiver: receiver, - MethodName: methodName, - Signature: signature, - FunctionBody: functionBody, - } -} - -// MethodElemNode represents the production -// -// MethodElem = MethodName Signature . -type MethodElemNode struct { - MethodName Token - Signature *SignatureNode - - typ Type -} - -// Source implements Node. -func (n *MethodElemNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *MethodElemNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.MethodName.Position() -} - -func (p *parser) methodElem() *MethodElemNode { - var ( - methodName Token - signature *SignatureNode - ) - // ebnf.Sequence MethodName Signature ctx [IDENT] - { - switch p.peek(1) { - case LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Name MethodName ctx [IDENT] - if methodName = p.methodName(); !methodName.IsValid() { - p.back(ix) - return nil - } - // *ebnf.Name Signature ctx [LPAREN] - if signature = p.signature(); signature == nil { - p.back(ix) - return nil - } - } - return &MethodElemNode{ - MethodName: methodName, - Signature: signature, - } -} - -// MethodExprNode represents the production -// -// MethodExpr = ReceiverType "." MethodName . -type MethodExprNode struct { - ReceiverType Node - PERIOD Token - MethodName Token -} - -// Source implements Node. -func (n *MethodExprNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *MethodExprNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.ReceiverType.Position() -} - -func (p *parser) methodExpr() *MethodExprNode { - var ( - ok bool - receiverType Node - periodTok Token - methodName Token - ) - // ebnf.Sequence ReceiverType "." MethodName ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - // *ebnf.Name ReceiverType ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if receiverType = p.type1(); receiverType == nil { - p.back(ix) - return nil - } - // *ebnf.Token "." ctx [] - if periodTok, ok = p.accept(PERIOD); !ok { - p.back(ix) - return nil - } - // *ebnf.Name MethodName ctx [] - switch p.c() { - case IDENT: - if methodName = p.methodName(); !methodName.IsValid() { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &MethodExprNode{ - ReceiverType: receiverType, - PERIOD: periodTok, - MethodName: methodName, - } -} - -func (p *parser) methodName() Token { - // *ebnf.Name identifier ctx [IDENT] - return p.expect(IDENT) -} - -func (p *parser) multiplicativeExpression(preBlock bool) (r Expression) { - var unaryExpr Expression - // ebnf.Sequence UnaryExpr { ( "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" ) UnaryExpr } ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name UnaryExpr ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if unaryExpr = p.unaryExpr(preBlock); unaryExpr == nil { - p.back(ix) - return nil - } - r = unaryExpr - // *ebnf.Repetition { ( "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" ) UnaryExpr } ctx [] - _0: - { - var op Token - var unaryExpr Expression - switch p.c() { - case AND, AND_NOT, MUL, QUO, REM, SHL, SHR: - // ebnf.Sequence ( "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" ) UnaryExpr ctx [AND, AND_NOT, MUL, QUO, REM, SHL, SHR] - // *ebnf.Group ( "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" ) ctx [AND, AND_NOT, MUL, QUO, REM, SHL, SHR] - // ebnf.Alternative "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" ctx [AND, AND_NOT, MUL, QUO, REM, SHL, SHR] - op = p.consume() - // *ebnf.Name UnaryExpr ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if unaryExpr = p.unaryExpr(preBlock); unaryExpr == nil { - p.back(ix) - goto _1 - } - default: - p.back(ix) - goto _1 - } - r = &BinaryExpressionNode{LHS: r, Op: op, RHS: unaryExpr} - goto _0 - } - _1: - } - } - return r -} - -// OperandNode represents the production -// -// Operand = Literal | OperandName [ TypeArgs ] [ LiteralValue ] . -type OperandNode struct { - OperandName Expression - TypeArgs *TypeArgsNode - LiteralValue *LiteralValueNode -} - -// Source implements Node. -func (n *OperandNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *OperandNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.OperandName.Position() -} - -type ParenthesizedExpressionNode struct { - LPAREN Token - Expression Expression - RPAREN Token -} - -// Source implements Node. -func (n *ParenthesizedExpressionNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ParenthesizedExpressionNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LPAREN.Position() -} - -func (p *parser) operand(preBlock bool) Expression { - var ( - ok bool - literal Expression - operandName Expression - typeArgs *TypeArgsNode - literalValue *LiteralValueNode - lparenTok Token - expression Expression - rparenTok Token - ) - // ebnf.Alternative Literal | OperandName [ TypeArgs ] [ LiteralValue ] | "(" Expression ")" ctx [CHAR, FLOAT, FUNC, IDENT, IMAG, INT, LBRACK, LPAREN, MAP, STRING, STRUCT] - switch p.c() { - case CHAR, FLOAT, FUNC, IMAG, INT, LBRACK, MAP, STRING, STRUCT: // 0 - // *ebnf.Name Literal ctx [CHAR, FLOAT, FUNC, IMAG, INT, LBRACK, MAP, STRING, STRUCT] - if literal = p.literal(); literal == nil { - return nil - } - return literal - case IDENT: // 1 - // ebnf.Sequence OperandName [ TypeArgs ] [ LiteralValue ] ctx [IDENT] - { - ix := p.ix - // *ebnf.Name OperandName ctx [IDENT] - if operandName = p.operandName(); operandName == nil { - p.back(ix) - goto _2 - } - // *ebnf.Option [ TypeArgs ] ctx [] - switch p.c() { - case LBRACK: - // *ebnf.Name TypeArgs ctx [LBRACK] - if typeArgs = p.typeArgs(); typeArgs == nil { - goto _4 - } - } - goto _5 - _4: - typeArgs = nil - _5: - if !preBlock { - // *ebnf.Option [ LiteralValue ] ctx [] - switch p.c() { - case LBRACE: - // *ebnf.Name LiteralValue ctx [LBRACE] - if literalValue = p.literalValue(); literalValue == nil { - goto _6 - } - } - goto _7 - _6: - literalValue = nil - _7: - } - } - break - _2: - literalValue = nil - operandName = nil - typeArgs = nil - return nil - case LPAREN: // 2 - // ebnf.Sequence "(" Expression ")" ctx [LPAREN] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _8 - } - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression == nil { - p.back(ix) - goto _8 - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - goto _8 - } - } - return &ParenthesizedExpressionNode{LPAREN: lparenTok, Expression: expression, RPAREN: rparenTok} - _8: - expression = nil - lparenTok = Token{} - rparenTok = Token{} - return nil - default: - return nil - } - if operandName != nil && typeArgs == nil && literalValue == nil { - return operandName - } - - return &OperandNode{ - OperandName: operandName, - TypeArgs: typeArgs, - LiteralValue: literalValue, - } -} - -// IotaNode represents the production -// -// IotaNode = identifier . -type IotaNode struct { - Iota Token - lexicalScoper -} - -// Source implements Node. -func (n *IotaNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *IotaNode) Position() (r token.Position) { - if n == nil || !n.Iota.IsValid() { - return r - } - - return n.Iota.Position() -} - -// OperandNameNode represents the production -// -// OperandName = identifier . -type OperandNameNode struct { - Name Token - lexicalScoper -} - -// Source implements Node. -func (n *OperandNameNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *OperandNameNode) Position() (r token.Position) { - if n == nil || !n.Name.IsValid() { - return r - } - - return n.Name.Position() -} - -// OperandQualifiedNameNode represents the production -// -// OperandQualifiedName = QualifiedIdent . -type OperandQualifiedNameNode struct { - Name *QualifiedIdentNode - lexicalScoper -} - -// Source implements Node. -func (n *OperandQualifiedNameNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *OperandQualifiedNameNode) Position() (r token.Position) { - if n == nil || n.Name == nil { - return r - } - - return n.Name.Position() -} - -func (p *parser) operandName() Expression { - var ( - qualifiedIdent *QualifiedIdentNode - ) - // ebnf.Alternative QualifiedIdent | identifier ctx [IDENT] - switch p.c() { - case IDENT: // 0 1 - // *ebnf.Name QualifiedIdent ctx [IDENT] - if qualifiedIdent = p.qualifiedIdent(); qualifiedIdent != nil { - return &OperandQualifiedNameNode{ - Name: qualifiedIdent, - lexicalScoper: newLexicalScoper(p.sc), - } - } - - // *ebnf.Name identifier ctx [IDENT] - return &OperandNameNode{ - Name: p.expect(IDENT), - lexicalScoper: newLexicalScoper(p.sc), - } - default: - return nil - } -} - -// PackageClauseNode represents the production -// -// PackageClause = "package" PackageName . -type PackageClauseNode struct { - PACKAGE Token - PackageName Token -} - -// Source implements Node. -func (n *PackageClauseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *PackageClauseNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.PACKAGE.Position() -} - -func (p *parser) packageClause() *PackageClauseNode { - var ( - packageTok Token - packageName Token - ) - // ebnf.Sequence "package" PackageName ctx [PACKAGE] - { - if p.peek(1) != IDENT { - return nil - } - ix := p.ix - // *ebnf.Token "package" ctx [PACKAGE] - packageTok = p.expect(PACKAGE) - // *ebnf.Name PackageName ctx [IDENT] - if packageName = p.packageName(); !packageName.IsValid() { - p.back(ix) - return nil - } - } - return &PackageClauseNode{ - PACKAGE: packageTok, - PackageName: packageName, - } -} - -func (p *parser) packageName() Token { - // *ebnf.Name identifier ctx [IDENT] - return p.expect(IDENT) -} - -// ParameterDeclNode represents the production -// -// ParameterDecl = [ IdentifierList ] [ "..." ] Type . -type ParameterDeclNode struct { - IdentifierList *IdentifierListNode - ELLIPSIS Token - TypeNode Type - - visible -} - -// Source implements Node. -func (n *ParameterDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ParameterDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.IdentifierList != nil { - return n.IdentifierList.Position() - } - - if n.ELLIPSIS.IsValid() { - return n.ELLIPSIS.Position() - } - - return n.TypeNode.Position() -} - -func (p *parser) parameterDecl() *ParameterDeclNode { - var ( - identTok Token - ellipsisTok Token - typeNode Type - ) - // ebnf.Alternative identifier "..." Type | identifier Type | "..." Type | Type ctx [ARROW, CHAN, ELLIPSIS, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - switch p.c() { - case IDENT: // 0 1 3 - // ebnf.Sequence identifier "..." Type ctx [IDENT] - { - if p.peek(1) != ELLIPSIS { - goto _0 - } - ix := p.ix - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - // *ebnf.Token "..." ctx [ELLIPSIS] - ellipsisTok = p.expect(ELLIPSIS) - // *ebnf.Name Type ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _0 - } - default: - p.back(ix) - goto _0 - } - } - break - _0: - ellipsisTok = Token{} - identTok = Token{} - typeNode = nil - // ebnf.Sequence identifier Type ctx [IDENT] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - goto _1 - } - ix := p.ix - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _1 - } - } - break - _1: - identTok = Token{} - typeNode = nil - // *ebnf.Name Type ctx [IDENT] - if typeNode = p.type1(); typeNode == nil { - goto _2 - } - break - _2: - typeNode = nil - return nil - case ELLIPSIS: // 2 - // ebnf.Sequence "..." Type ctx [ELLIPSIS] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - goto _3 - } - ix := p.ix - // *ebnf.Token "..." ctx [ELLIPSIS] - ellipsisTok = p.expect(ELLIPSIS) - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _3 - } - } - break - _3: - ellipsisTok = Token{} - typeNode = nil - return nil - case ARROW, CHAN, FUNC, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: // 3 - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - goto _5 - } - break - _5: - typeNode = nil - return nil - default: - return nil - } - var idl *IdentifierListNode - if identTok.IsValid() { - idl = &IdentifierListNode{IDENT: identTok} - } - return &ParameterDeclNode{ - IdentifierList: idl, - ELLIPSIS: ellipsisTok, - TypeNode: typeNode, - } -} - -// ParameterDeclListNode represents the production -// -// ParameterDeclListNode = { ParameterDecl "," } . -type ParameterDeclListNode struct { - ParameterDecl *ParameterDeclNode - COMMA Token - List *ParameterDeclListNode -} - -// Source implements Node. -func (n *ParameterDeclListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ParameterDeclListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.ParameterDecl.Position() -} - -// ParametersNode represents the production -// -// Parameters = "(" { ParameterDecl "," } ")" . -type ParametersNode struct { - LPAREN Token - ParameterDeclList *ParameterDeclListNode - RPAREN Token -} - -// Source implements Node. -func (n *ParametersNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ParametersNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LPAREN.Position() -} - -func (p *parser) parameters() (r *ParametersNode) { - var ( - ok bool - lparenTok Token - parameterDecl *ParameterDeclNode - list0 []*ParameterDeclListNode - list, last *ParameterDeclListNode - rparenTok Token - ) - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - for { - // *ebnf.Option [ ParameterList [ "," ] ] ctx [] - switch p.c() { - case ARROW, CHAN, ELLIPSIS, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - // ebnf.Sequence ParameterList [ "," ] ctx [ARROW, CHAN, ELLIPSIS, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - if parameterDecl = p.parameterDecl(); parameterDecl == nil { - p.back(ix) - goto _1 - } - // *ebnf.Option [ "," ] ctx [] - switch p.c() { - case COMMA: - // *ebnf.Token "," ctx [COMMA] - next := &ParameterDeclListNode{ - ParameterDecl: parameterDecl, - COMMA: p.consume(), - } - list0 = append(list0, next) - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - continue - case RPAREN: - next := &ParameterDeclListNode{ - ParameterDecl: parameterDecl, - } - list0 = append(list0, next) - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - } - } - } - goto _1 - } -_1: - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - return nil - } - var ids []int - for i, v := range list0 { - if v.ParameterDecl.IdentifierList != nil { - ids = append(ids, i) - } - } - r = &ParametersNode{ - LPAREN: lparenTok, - ParameterDeclList: list, - RPAREN: rparenTok, - } - if len(ids) != 0 && len(ids) != len(list0) { - // len(ids) - // | ids - // | | len(list0) - // TODO gc.go:74:20 (rel, importPath, version string) 1 [2] 3 - last = nil - for _, v := range list0 { - x := *v - x.List = nil - } - for firstX := 0; len(ids) != 0; { - lastX := ids[0] - ids = ids[1:] - grp := list0[lastX] - grp.List = nil - idl := grp.ParameterDecl.IdentifierList - for i := lastX - 1; i >= firstX; i-- { - item := list0[i] - decl := item.ParameterDecl - typ := decl.TypeNode - switch x := typ.(type) { - case *TypeNode: - if x.TypeArgs != nil { - panic(todo("%v: %s", decl.Position(), decl.Source(false))) - } - - if x.TypeName == nil { - p.err(x.Position(), "syntax error: mixed named and unnamed parameters") - continue - } - - switch y := x.TypeName.Name.(type) { - case Token: - // { param , } vs { , ident } - idl.COMMA = item.COMMA - li := &IdentifierListNode{IDENT: y} - li.List = idl - idl = li - default: - p.err(y.Position(), "syntax error: mixed named and unnamed parameters") - } - case *TypeNameNode: - switch y := x.Name.(type) { - case Token: - // { param , } vs { , ident } - idl.COMMA = item.COMMA - li := &IdentifierListNode{IDENT: y} - li.List = idl - idl = li - default: - p.err(y.Position(), "syntax error: mixed named and unnamed parameters") - } - default: - p.err(x.Position(), "syntax error: mixed named and unnamed parameters") - } - } - grp.ParameterDecl.IdentifierList = idl - firstX = lastX + 1 - if last == nil { - r.ParameterDeclList = grp - last = grp - continue - } - - last.List = grp - last = grp - } - } - return r -} - -func (n *ParametersNode) declare(p *parser, s *Scope) { - if n == nil { - return - } - - for l := n.ParameterDeclList; l != nil; l = l.List { - pd := l.ParameterDecl - for l := pd.IdentifierList; l != nil; l = l.List { - p.declare(s, l.IDENT, pd, 0, true) - } - } -} - -// PointerTypeNode represents the production -// -// PointerType = "*" BaseType . -type PointerTypeNode struct { - MUL Token - BaseType Type - - guard -} - -// Source implements Node. -func (n *PointerTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *PointerTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.MUL.Position() -} - -func (p *parser) pointerType() *PointerTypeNode { - var ( - mulTok Token - baseType Type - ) - // ebnf.Sequence "*" BaseType ctx [MUL] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - return nil - } - ix := p.ix - // *ebnf.Token "*" ctx [MUL] - mulTok = p.expect(MUL) - // *ebnf.Name BaseType ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if baseType = p.type1(); baseType == nil { - p.back(ix) - return nil - } - } - return &PointerTypeNode{ - MUL: mulTok, - BaseType: baseType, - } -} - -func (p *parser) postStmt() Node { - // *ebnf.Name SimpleStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */] - return p.simpleStmt(true) -} - -// PrimaryExprNode represents the production -// -// PrimaryExpr = Operand | Conversion | MethodExpr { Selector | Index | Slice | TypeAssertion | Arguments } . -type PrimaryExprNode struct { - PrimaryExpr Expression - Postfix Node -} - -// Source implements Node. -func (n *PrimaryExprNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *PrimaryExprNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.PrimaryExpr.Position() -} - -func (p *parser) primaryExpr(preBlock bool) (r Expression) { - var ( - item0 Expression - operand Expression - conversion *ConversionNode - methodExpr *MethodExprNode - list []Node - ) - // ebnf.Sequence ( Operand | Conversion | MethodExpr ) { Selector | Index | Slice | TypeAssertion | Arguments } ctx [ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT] - { - ix := p.ix - // *ebnf.Group ( Operand | Conversion | MethodExpr ) ctx [ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT] - // ebnf.Alternative Operand | Conversion | MethodExpr ctx [ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT] - switch p.c() { - case CHAR, FLOAT, IMAG, INT, STRING: // 0 - // *ebnf.Name Operand ctx [CHAR, FLOAT, IMAG, INT, STRING] - if operand = p.operand(preBlock); operand == nil { - goto _0 - } - item0 = operand - break - _0: - operand = nil - p.back(ix) - return nil - case FUNC, IDENT, LBRACK, LPAREN, MAP, STRUCT: // 0 1 2 - // *ebnf.Name Operand ctx [FUNC, IDENT, LBRACK, LPAREN, MAP, STRUCT] - if operand = p.operand(preBlock); operand == nil { - goto _2 - } - item0 = operand - break - _2: - operand = nil - // *ebnf.Name Conversion ctx [FUNC, IDENT, LBRACK, LPAREN, MAP, STRUCT] - if conversion = p.conversion(); conversion == nil { - goto _3 - } - item0 = conversion - break - _3: - conversion = nil - // *ebnf.Name MethodExpr ctx [FUNC, IDENT, LBRACK, LPAREN, MAP, STRUCT] - if methodExpr = p.methodExpr(); methodExpr == nil { - goto _4 - } - item0 = methodExpr - break - _4: - methodExpr = nil - p.back(ix) - return nil - case ARROW, CHAN, INTERFACE, MUL: // 1 2 - // *ebnf.Name Conversion ctx [ARROW, CHAN, INTERFACE, MUL] - if conversion = p.conversion(); conversion == nil { - goto _5 - } - item0 = conversion - break - _5: - conversion = nil - // *ebnf.Name MethodExpr ctx [ARROW, CHAN, INTERFACE, MUL] - if methodExpr = p.methodExpr(); methodExpr == nil { - goto _6 - } - item0 = methodExpr - break - _6: - methodExpr = nil - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - - r = item0 - - // *ebnf.Repetition { Selector | Index | Slice | TypeAssertion | Arguments } ctx [] - _7: - { - var item Node - var selector *SelectorNode - var index *IndexNode - var slice *SliceNode - var typeAssertion *TypeAssertionNode - var arguments Node - switch p.c() { - case LBRACK, LPAREN, PERIOD: - // ebnf.Alternative Selector | Index | Slice | TypeAssertion | Arguments ctx [LBRACK, LPAREN, PERIOD] - switch p.c() { - case PERIOD: // 0 3 - // *ebnf.Name Selector ctx [PERIOD] - if selector = p.selector(); selector == nil { - goto _9 - } - item = selector - break - _9: - // *ebnf.Name TypeAssertion ctx [PERIOD] - if typeAssertion = p.typeAssertion(); typeAssertion == nil { - goto _10 - } - item = typeAssertion - break - _10: - goto _8 - case LBRACK: // 1 2 - // *ebnf.Name Index ctx [LBRACK] - if index = p.index(); index == nil { - goto _11 - } - item = index - break - _11: - // *ebnf.Name Slice ctx [LBRACK] - if slice = p.slice(); slice == nil { - goto _12 - } - item = slice - break - _12: - goto _8 - case LPAREN: // 4 - // *ebnf.Name Arguments ctx [LPAREN] - if arguments = p.arguments(); arguments == nil { - goto _13 - } - item = arguments - break - _13: - goto _8 - default: - goto _8 - } - list = append(list, item) - r = &PrimaryExprNode{PrimaryExpr: r, Postfix: item} - goto _7 - } - _8: - } - } - return r -} - -// QualifiedIdentNode represents the production -// -// QualifiedIdent = PackageName "." identifier . -type QualifiedIdentNode struct { - PackageName Token - PERIOD Token - IDENT Token -} - -// Source implements Node. -func (n *QualifiedIdentNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *QualifiedIdentNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.PackageName.Position() -} - -func (p *parser) qualifiedIdent() *QualifiedIdentNode { - var ( - ok bool - packageName Token - periodTok Token - identTok Token - ) - // ebnf.Sequence PackageName "." identifier ctx [IDENT] - { - if p.peek(1) != PERIOD { - return nil - } - ix := p.ix - // *ebnf.Name PackageName ctx [IDENT] - if packageName = p.packageName(); !packageName.IsValid() { - p.back(ix) - return nil - } - // *ebnf.Token "." ctx [PERIOD] - periodTok = p.expect(PERIOD) - // *ebnf.Name identifier ctx [] - if identTok, ok = p.accept(IDENT); !ok { - p.back(ix) - return nil - } - } - return &QualifiedIdentNode{ - PackageName: packageName, - PERIOD: periodTok, - IDENT: identTok, - } -} - -// RangeClauseNode represents the production -// -// RangeClause = "range" Expression | ExpressionList "=" "range" Expression | IdentifierList ":=" "range" Expression . -type RangeClauseNode struct { - RANGE Token - Expression Expression - ExpressionList *ExpressionListNode - ASSIGN Token - IdentifierList *IdentifierListNode - DEFINE Token -} - -// Source implements Node. -func (n *RangeClauseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *RangeClauseNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) rangeClause() *RangeClauseNode { - var ( - ok bool - rangeTok Token - expression Expression - expressionList *ExpressionListNode - assignTok Token - identifierList *IdentifierListNode - defineTok Token - ) - // ebnf.Alternative "range" Expression | ExpressionList "=" "range" Expression | IdentifierList ":=" "range" Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, RANGE, STRING, STRUCT, SUB, XOR] - switch p.c() { - case RANGE: // 0 - // ebnf.Sequence "range" Expression ctx [RANGE] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _0 - } - ix := p.ix - // *ebnf.Token "range" ctx [RANGE] - rangeTok = p.expect(RANGE) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(true); expression == nil { - p.back(ix) - goto _0 - } - } - break - _0: - expression = nil - rangeTok = Token{} - return nil - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: // 1 - // ebnf.Sequence ExpressionList "=" "range" Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _2 - } - // *ebnf.Token "=" ctx [] - if assignTok, ok = p.accept(ASSIGN); !ok { - p.back(ix) - goto _2 - } - // *ebnf.Token "range" ctx [] - if rangeTok, ok = p.accept(RANGE); !ok { - p.back(ix) - goto _2 - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression = p.expression(true); expression == nil { - p.back(ix) - goto _2 - } - default: - p.back(ix) - goto _2 - } - } - break - _2: - assignTok = Token{} - expressionList = nil - expression = nil - rangeTok = Token{} - return nil - case IDENT: // 1 2 - // ebnf.Sequence ExpressionList "=" "range" Expression ctx [IDENT] - { - ix := p.ix - // *ebnf.Name ExpressionList ctx [IDENT] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _4 - } - // *ebnf.Token "=" ctx [] - if assignTok, ok = p.accept(ASSIGN); !ok { - p.back(ix) - goto _4 - } - // *ebnf.Token "range" ctx [] - if rangeTok, ok = p.accept(RANGE); !ok { - p.back(ix) - goto _4 - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression = p.expression(true); expression == nil { - p.back(ix) - goto _4 - } - default: - p.back(ix) - goto _4 - } - } - break - _4: - assignTok = Token{} - expressionList = nil - expression = nil - rangeTok = Token{} - // ebnf.Sequence IdentifierList ":=" "range" Expression ctx [IDENT] - { - ix := p.ix - // *ebnf.Name IdentifierList ctx [IDENT] - if identifierList = p.identifierList(); identifierList == nil { - p.back(ix) - goto _5 - } - // *ebnf.Token ":=" ctx [] - if defineTok, ok = p.accept(DEFINE); !ok { - p.back(ix) - goto _5 - } - // *ebnf.Token "range" ctx [] - if rangeTok, ok = p.accept(RANGE); !ok { - p.back(ix) - goto _5 - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression = p.expression(true); expression == nil { - p.back(ix) - goto _5 - } - default: - p.back(ix) - goto _5 - } - } - break - _5: - defineTok = Token{} - expression = nil - identifierList = nil - rangeTok = Token{} - return nil - default: - return nil - } - return &RangeClauseNode{ - RANGE: rangeTok, - Expression: expression, - ExpressionList: expressionList, - ASSIGN: assignTok, - IdentifierList: identifierList, - DEFINE: defineTok, - } -} - -func (p *parser) receiver() *ParametersNode { - // *ebnf.Name Parameters ctx [LPAREN] - return p.parameters() -} - -func (p *parser) recvExpr() Expression { - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - return p.expression(false) -} - -// RecvStmtNode represents the production -// -// RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . -type RecvStmtNode struct { - ExpressionList *ExpressionListNode - Token Token - IdentifierList *IdentifierListNode - RecvExpr Expression -} - -// Source implements Node. -func (n *RecvStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *RecvStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) recvStmt() *RecvStmtNode { - var ( - ok bool - expressionList *ExpressionListNode - tok Token - identifierList *IdentifierListNode - recvExpr Expression - ) - // ebnf.Sequence [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Option [ ExpressionList "=" | IdentifierList ":=" ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - // ebnf.Alternative ExpressionList "=" | IdentifierList ":=" ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: // 0 - // ebnf.Sequence ExpressionList "=" ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _2 - } - // *ebnf.Token "=" ctx [] - if tok, ok = p.accept(ASSIGN); !ok { - p.back(ix) - goto _2 - } - } - break - _2: - tok = Token{} - expressionList = nil - goto _0 - case IDENT: // 0 1 - // ebnf.Sequence ExpressionList "=" ctx [IDENT] - { - ix := p.ix - // *ebnf.Name ExpressionList ctx [IDENT] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _4 - } - // *ebnf.Token "=" ctx [] - if tok, ok = p.accept(ASSIGN); !ok { - p.back(ix) - goto _4 - } - } - break - _4: - tok = Token{} - expressionList = nil - // ebnf.Sequence IdentifierList ":=" ctx [IDENT] - { - ix := p.ix - // *ebnf.Name IdentifierList ctx [IDENT] - if identifierList = p.identifierList(); identifierList == nil { - p.back(ix) - goto _5 - } - // *ebnf.Token ":=" ctx [] - if tok, ok = p.accept(DEFINE); !ok { - p.back(ix) - goto _5 - } - } - break - _5: - tok = Token{} - identifierList = nil - goto _0 - default: - goto _0 - } - goto _1 - _0: - tok = Token{} - expressionList = nil - _1: - // *ebnf.Name RecvExpr ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if recvExpr = p.recvExpr(); recvExpr == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &RecvStmtNode{ - ExpressionList: expressionList, - Token: tok, - IdentifierList: identifierList, - RecvExpr: recvExpr, - } -} - -func (p *parser) relationalExpression(preBlock bool) (r Expression) { - var additiveExpression Expression - // ebnf.Sequence AdditiveExpression { ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) AdditiveExpression } ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name AdditiveExpression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if additiveExpression = p.additiveExpression(preBlock); additiveExpression == nil { - p.back(ix) - return nil - } - r = additiveExpression - // *ebnf.Repetition { ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) AdditiveExpression } ctx [] - _0: - { - var op Token - var additiveExpression Expression - switch p.c() { - case EQL, GEQ, GTR, LEQ, LSS, NEQ: - // ebnf.Sequence ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) AdditiveExpression ctx [EQL, GEQ, GTR, LEQ, LSS, NEQ] - // *ebnf.Group ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) ctx [EQL, GEQ, GTR, LEQ, LSS, NEQ] - // ebnf.Alternative "==" | "!=" | "<" | "<=" | ">" | ">=" ctx [EQL, GEQ, GTR, LEQ, LSS, NEQ] - op = p.consume() - // *ebnf.Name AdditiveExpression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if additiveExpression = p.additiveExpression(preBlock); additiveExpression == nil { - p.back(ix) - goto _1 - } - default: - p.back(ix) - goto _1 - } - r = &BinaryExpressionNode{LHS: r, Op: op, RHS: additiveExpression} - goto _0 - } - _1: - } - } - return r -} - -// ResultNode represents the production -// -// Result = Parameters | Type . -type ResultNode struct { - Parameters *ParametersNode - TypeNode Type -} - -// Source implements Node. -func (n *ResultNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ResultNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.Parameters != nil { - return n.Parameters.Position() - } - - return n.TypeNode.Position() -} - -func (p *parser) result() *ResultNode { - var ( - parameters *ParametersNode - typeNode Type - ) - // ebnf.Alternative Parameters | Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - switch p.c() { - case LPAREN: // 0 1 - // *ebnf.Name Parameters ctx [LPAREN] - if parameters = p.parameters(); parameters == nil { - goto _0 - } - break - _0: - parameters = nil - // *ebnf.Name Type ctx [LPAREN] - if typeNode = p.type1(); typeNode == nil { - goto _1 - } - break - _1: - typeNode = nil - return nil - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, MAP, MUL, STRUCT: // 1 - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - goto _2 - } - break - _2: - typeNode = nil - return nil - default: - return nil - } - return &ResultNode{ - Parameters: parameters, - TypeNode: typeNode, - } -} - -// ReturnStmtNode represents the production -// -// ReturnStmt = "return" [ ExpressionList ] . -type ReturnStmtNode struct { - RETURN Token - ExpressionList *ExpressionListNode -} - -// Source implements Node. -func (n *ReturnStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ReturnStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.RETURN.Position() -} - -func (p *parser) returnStmt() *ReturnStmtNode { - var ( - returnTok Token - expressionList *ExpressionListNode - ) - // ebnf.Sequence "return" [ ExpressionList ] ctx [RETURN] - { - // *ebnf.Token "return" ctx [RETURN] - returnTok = p.expect(RETURN) - // *ebnf.Option [ ExpressionList ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - goto _0 - } - } - goto _1 - _0: - expressionList = nil - _1: - } - return &ReturnStmtNode{ - RETURN: returnTok, - ExpressionList: expressionList, - } -} - -// CommClauseListNode represents the production -// -// CommClauseListNode = { CommClause } . -type CommClauseListNode struct { - CommClause *CommClauseNode - List *CommClauseListNode -} - -// Source implements Node. -func (n *CommClauseListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *CommClauseListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.CommClause.Position() -} - -// SelectStmtNode represents the production -// -// SelectStmt = "select" "{" { CommClause } "}" . -type SelectStmtNode struct { - SELECT Token - LBRACE Token - CommClauseList *CommClauseListNode - RBRACE Token -} - -// Source implements Node. -func (n *SelectStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SelectStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.SELECT.Position() -} - -func (p *parser) selectStmt() *SelectStmtNode { - var ( - ok bool - selectTok Token - lbraceTok Token - list, last *CommClauseListNode - rbraceTok Token - ) - // ebnf.Sequence "select" "{" { CommClause } "}" ctx [SELECT] - { - if p.peek(1) != LBRACE { - return nil - } - ix := p.ix - // *ebnf.Token "select" ctx [SELECT] - selectTok = p.expect(SELECT) - // *ebnf.Token "{" ctx [LBRACE] - lbraceTok = p.expect(LBRACE) - // *ebnf.Repetition { CommClause } ctx [] - _0: - { - var commClause *CommClauseNode - switch p.c() { - case CASE, DEFAULT: - // *ebnf.Name CommClause ctx [CASE, DEFAULT] - if commClause = p.commClause(); commClause == nil { - goto _1 - } - next := &CommClauseListNode{ - CommClause: commClause, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _0 - } - _1: - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - return nil - } - } - return &SelectStmtNode{ - SELECT: selectTok, - LBRACE: lbraceTok, - CommClauseList: list, - RBRACE: rbraceTok, - } -} - -// SelectorNode represents the production -// -// Selector = "." identifier . -type SelectorNode struct { - PERIOD Token - IDENT Token -} - -// Source implements Node. -func (n *SelectorNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SelectorNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.PERIOD.Position() -} - -func (p *parser) selector() *SelectorNode { - var ( - periodTok Token - identTok Token - ) - // ebnf.Sequence "." identifier ctx [PERIOD] - { - if p.peek(1) != IDENT { - return nil - } - // *ebnf.Token "." ctx [PERIOD] - periodTok = p.expect(PERIOD) - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - } - return &SelectorNode{ - PERIOD: periodTok, - IDENT: identTok, - } -} - -// SendStmtNode represents the production -// -// SendStmt = Channel "<-" Expression . -type SendStmtNode struct { - Channel Expression - ARROW Token - Expression Expression -} - -// Source implements Node. -func (n *SendStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SendStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Channel.Position() -} - -func (p *parser) sendStmt() *SendStmtNode { - var ( - ok bool - channel Expression - arrowTok Token - expression Expression - ) - // ebnf.Sequence Channel "<-" Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name Channel ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if channel = p.channel(); channel == nil { - p.back(ix) - return nil - } - // *ebnf.Token "<-" ctx [] - if arrowTok, ok = p.accept(ARROW); !ok { - p.back(ix) - return nil - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression = p.expression(false); expression == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &SendStmtNode{ - Channel: channel, - ARROW: arrowTok, - Expression: expression, - } -} - -// ShortVarDeclNode represents the production -// -// ShortVarDecl = IdentifierList ":=" ExpressionList . -type ShortVarDeclNode struct { - IdentifierList *IdentifierListNode - DEFINE Token - ExpressionList *ExpressionListNode - - visible -} - -// Source implements Node. -func (n *ShortVarDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ShortVarDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IdentifierList.Position() -} - -func (p *parser) shortVarDecl(lhs *ExpressionListNode, preBlock bool) (r *ShortVarDeclNode) { - var ( - defineTok Token - expressionList *ExpressionListNode - ) - // ebnf.Sequence ":=" ExpressionList ctx [DEFINE] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - return nil - } - ix := p.ix - // *ebnf.Token ":=" ctx [DEFINE] - defineTok = p.expect(DEFINE) - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(preBlock); expressionList == nil { - p.back(ix) - return nil - } - } - list := p.exprList2identList(lhs) - sc := p.sc - r = &ShortVarDeclNode{ - IdentifierList: list, - DEFINE: defineTok, - ExpressionList: expressionList, - } - visible := int32(p.ix) - hasNew := false - for n := r.IdentifierList; n != nil; n = n.List { - id := n.IDENT - ex := sc.declare(id, r, visible, p, false) - if !ex.declTok.IsValid() { - hasNew = true - } - } - if !hasNew { - for n := r.IdentifierList; n != nil; n = n.List { - id := n.IDENT - nm := id.Src() - ex := sc.nodes[nm] - if ex.declTok.IsValid() { - p.err(id.Position(), "%s redeclared, previous declaration at %v: (%p)", nm, ex.declTok.Position(), sc) - } - } - } - return r -} - -func (p *parser) exprList2identList(list *ExpressionListNode) (r *IdentifierListNode) { - var last *IdentifierListNode - for n := list; n != nil; n = n.List { - next := &IdentifierListNode{ - COMMA: n.COMMA, - IDENT: p.expr2ident(n.Expression), - } - if !next.IDENT.IsValid() { - continue - } - - if r == nil { - r = next - } - if last != nil { - last.List = next - } - last = next - } - return r -} - -func (p *parser) expr2ident(e Expression) (r Token) { - switch x := e.(type) { - case *OperandNode: - if (x.TypeArgs != nil || x.LiteralValue != nil) && p.reportDeclarationErrors { - p.err(x.Position(), "expected identifier") - break - } - - return p.expr2ident(x.OperandName) - case *OperandNameNode: - return x.Name - - p.err(x.Position(), "expected identifier") - default: - if p.reportDeclarationErrors { - p.err(x.Position(), "expected identifier") - } - } - return r -} - -// SignatureNode represents the production -// -// Signature = Parameters [ Result ] . -type SignatureNode struct { - Parameters *ParametersNode - Result *ResultNode - - typeCache -} - -// Source implements Node. -func (n *SignatureNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SignatureNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Parameters.Position() -} - -func (p *parser) signature() *SignatureNode { - var ( - parameters *ParametersNode - result *ResultNode - ) - // ebnf.Sequence Parameters [ Result ] ctx [LPAREN] - { - ix := p.ix - // *ebnf.Name Parameters ctx [LPAREN] - if parameters = p.parameters(); parameters == nil { - p.back(ix) - return nil - } - // *ebnf.Option [ Result ] ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - // *ebnf.Name Result ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if result = p.result(); result == nil { - goto _0 - } - } - goto _1 - _0: - result = nil - _1: - } - return &SignatureNode{ - Parameters: parameters, - Result: result, - } -} - -// IncDecStmtNode represents the production -// -// IncDecStmt = Expression ( "++" | "--" ) . -type IncDecStmtNode struct { - Expression Expression - Token Token -} - -// Source implements Node. -func (n *IncDecStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *IncDecStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Expression.Position() -} - -func (p *parser) simpleStmt(preBlock bool) Node { - var ( - expressionList *ExpressionListNode - assignment *AssignmentNode - shortVarDecl *ShortVarDeclNode - arrowTok Token - expression Expression - emptyStmt *EmptyStmtNode - ) - // ebnf.Alternative ExpressionList [ Assignment | ShortVarDecl | "<-" Expression | "++" | "--" ] | EmptyStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: // 0 - // ebnf.Sequence ExpressionList [ Assignment | ShortVarDecl | "<-" Expression | "++" | "--" ] ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(preBlock); expressionList == nil { - p.back(ix) - goto _0 - } - // *ebnf.Option [ Assignment | ShortVarDecl | "<-" Expression | "++" | "--" ] ctx [] - switch p.c() { - case ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ARROW, ASSIGN, DEC, DEFINE, INC, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN: - // ebnf.Alternative Assignment | ShortVarDecl | "<-" Expression | "++" | "--" ctx [ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ARROW, ASSIGN, DEC, DEFINE, INC, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN] - switch p.c() { - case ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ASSIGN, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN: // 0 - // *ebnf.Name Assignment ctx [ADD_ASSIGN, AND_ASSIGN, AND_NOT_ASSIGN, ASSIGN, MUL_ASSIGN, OR_ASSIGN, QUO_ASSIGN, REM_ASSIGN, SHL_ASSIGN, SHR_ASSIGN, SUB_ASSIGN, XOR_ASSIGN] - if assignment = p.assignment(expressionList, preBlock); assignment == nil { - goto _4 - } - return assignment - _4: - assignment = nil - goto _2 - case DEFINE: // 1 - // *ebnf.Name ShortVarDecl ctx [DEFINE] - if shortVarDecl = p.shortVarDecl(expressionList, preBlock); shortVarDecl == nil { - goto _6 - } - return shortVarDecl - _6: - shortVarDecl = nil - goto _2 - case ARROW: // 2 - // ebnf.Sequence "<-" Expression ctx [ARROW] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _8 - } - ix := p.ix - // *ebnf.Token "<-" ctx [ARROW] - arrowTok = p.expect(ARROW) - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(preBlock); expression == nil { - p.back(ix) - goto _8 - } - } - if expressionList.Len() > 1 { - p.err(expressionList.Position(), "expected one expression: %s", expressionList.Source(false)) - } - return &SendStmtNode{ - Channel: expressionList.first(), - ARROW: arrowTok, - Expression: expression, - } - - _8: - arrowTok = Token{} - expression = nil - goto _2 - case INC: // 3 - // *ebnf.Token "++" ctx [INC] - if expressionList.Len() > 1 { - p.err(expressionList.Position(), "expected one expression: %s", expressionList.Source(false)) - } - return &IncDecStmtNode{ - Expression: expressionList.first(), - Token: p.expect(INC), - } - case DEC: // 4 - // *ebnf.Token "--" ctx [DEC] - if expressionList.Len() > 1 { - p.err(expressionList.Position(), "expected one expression: %s", expressionList.Source(false)) - } - return &IncDecStmtNode{ - Expression: expressionList.first(), - Token: p.expect(DEC), - } - default: - goto _2 - } - } - goto _3 - _2: - arrowTok = Token{} - assignment = nil - expression = nil - shortVarDecl = nil - _3: - } - break - _0: - arrowTok = Token{} - assignment = nil - expression = nil - expressionList = nil - shortVarDecl = nil - return nil - default: // /* ε */ 1 - // *ebnf.Name EmptyStmt ctx [ /* ε */] - if emptyStmt = p.emptyStmt(); emptyStmt == nil { - goto _14 - } - return emptyStmt - _14: - emptyStmt = nil - return nil - } - if expressionList == nil || expressionList.Len() > 1 { - return nil - } - - return expressionList.first() -} - -// SliceNode represents the production -// -// Slice = "[" [ Expression ] ":" [ Expression ] "]" | "[" [ Expression ] ":" Expression ":" Expression "]" . -type SliceNode struct { - LBRACK Token - Expression Expression - COLON Token - Expression2 Expression - RBRACK Token - COLON2 Token - Expression3 Expression -} - -// Source implements Node. -func (n *SliceNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SliceNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) slice() *SliceNode { - var ( - ok bool - lbrackTok Token - expression Expression - colonTok Token - expression2 Expression - rbrackTok Token - colon2Tok Token - expression3 Expression - ) - // ebnf.Alternative "[" [ Expression ] ":" [ Expression ] "]" | "[" [ Expression ] ":" Expression ":" Expression "]" ctx [LBRACK] - switch p.c() { - case LBRACK: // 0 1 - // ebnf.Sequence "[" [ Expression ] ":" [ Expression ] "]" ctx [LBRACK] - { - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Option [ Expression ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression == nil { - goto _1 - } - } - goto _2 - _1: - expression = nil - _2: - // *ebnf.Token ":" ctx [] - if colonTok, ok = p.accept(COLON); !ok { - p.back(ix) - goto _0 - } - // *ebnf.Option [ Expression ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression2 = p.expression(false); expression2 == nil { - goto _3 - } - } - goto _4 - _3: - expression2 = nil - _4: - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - goto _0 - } - } - break - _0: - colonTok = Token{} - expression = nil - expression2 = nil - lbrackTok = Token{} - rbrackTok = Token{} - // ebnf.Sequence "[" [ Expression ] ":" Expression ":" Expression "]" ctx [LBRACK] - { - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Option [ Expression ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - // *ebnf.Name Expression ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expression = p.expression(false); expression == nil { - goto _6 - } - } - goto _7 - _6: - expression = nil - _7: - // *ebnf.Token ":" ctx [] - if colonTok, ok = p.accept(COLON); !ok { - p.back(ix) - goto _5 - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression2 = p.expression(false); expression2 == nil { - p.back(ix) - goto _5 - } - default: - p.back(ix) - goto _5 - } - // *ebnf.Token ":" ctx [] - if colon2Tok, ok = p.accept(COLON); !ok { - p.back(ix) - goto _5 - } - // *ebnf.Name Expression ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if expression3 = p.expression(false); expression3 == nil { - p.back(ix) - goto _5 - } - default: - p.back(ix) - goto _5 - } - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - goto _5 - } - } - break - _5: - colon2Tok = Token{} - colonTok = Token{} - expression = nil - expression2 = nil - expression3 = nil - lbrackTok = Token{} - rbrackTok = Token{} - return nil - default: - return nil - } - return &SliceNode{ - LBRACK: lbrackTok, - Expression: expression, - COLON: colonTok, - Expression2: expression2, - RBRACK: rbrackTok, - COLON2: colon2Tok, - Expression3: expression3, - } -} - -// SliceTypeNode represents the production -// -// SliceType = "[" "]" ElementType . -type SliceTypeNode struct { - LBRACK Token - RBRACK Token - ElementType Node - - guard -} - -// Source implements Node. -func (n *SliceTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SliceTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACK.Position() -} - -func (p *parser) sliceType() *SliceTypeNode { - var ( - lbrackTok Token - rbrackTok Token - elementType Node - ) - // ebnf.Sequence "[" "]" ElementType ctx [LBRACK] - { - if p.peek(1) != RBRACK { - return nil - } - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Token "]" ctx [RBRACK] - rbrackTok = p.expect(RBRACK) - // *ebnf.Name ElementType ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if elementType = p.type1(); elementType == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &SliceTypeNode{ - LBRACK: lbrackTok, - RBRACK: rbrackTok, - ElementType: elementType, - } -} - -// ImportDeclListNode represents the production -// -// ImportDeclListNode = { ImportDecl ";" } . -type ImportDeclListNode struct { - ImportDecl *ImportDeclNode - SEMICOLON Token - List *ImportDeclListNode -} - -// Source implements Node. -func (n *ImportDeclListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ImportDeclListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.ImportDecl.Position() -} - -// TopLevelDeclListNode represents the production -// -// TopLevelDeclListNode = { TopLevelDecl ";" . -type TopLevelDeclListNode struct { - TopLevelDecl Node - SEMICOLON Token - List *TopLevelDeclListNode -} - -// Source implements Node. -func (n *TopLevelDeclListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TopLevelDeclListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TopLevelDecl.Position() -} - -// SourceFileNode represents the production -// -// SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . -type SourceFileNode struct { - PackageClause *PackageClauseNode - SEMICOLON Token - ImportDeclList *ImportDeclListNode - TopLevelDeclList *TopLevelDeclListNode -} - -// Source implements Node. -func (n *SourceFileNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SourceFileNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.PackageClause.Position() -} - -func (p *parser) sourceFile() *SourceFileNode { - var ( - ok bool - packageClause *PackageClauseNode - semicolonTok Token - list, last *ImportDeclListNode - list2, last2 *TopLevelDeclListNode - ) - // ebnf.Sequence PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } ctx [PACKAGE] - { - ix := p.ix - // *ebnf.Name PackageClause ctx [PACKAGE] - if packageClause = p.packageClause(); packageClause == nil { - p.back(ix) - return nil - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - return nil - } - // *ebnf.Repetition { ImportDecl ";" } ctx [] - _0: - { - var importDecl *ImportDeclNode - var semicolonTok Token - switch p.c() { - case IMPORT: - // ebnf.Sequence ImportDecl ";" ctx [IMPORT] - ix := p.ix - // *ebnf.Name ImportDecl ctx [IMPORT] - if importDecl = p.importDecl(); importDecl == nil { - p.back(ix) - goto _1 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _1 - } - next := &ImportDeclListNode{ - ImportDecl: importDecl, - SEMICOLON: semicolonTok, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _0 - } - _1: - } - // *ebnf.Repetition { TopLevelDecl ";" } ctx [] - _2: - { - var topLevelDecl Node - var semicolonTok Token - switch p.c() { - case CONST, FUNC, TYPE, VAR: - // ebnf.Sequence TopLevelDecl ";" ctx [CONST, FUNC, TYPE, VAR] - ix := p.ix - // *ebnf.Name TopLevelDecl ctx [CONST, FUNC, TYPE, VAR] - if topLevelDecl = p.topLevelDecl(); topLevelDecl == nil { - p.back(ix) - goto _3 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _3 - } - next := &TopLevelDeclListNode{ - TopLevelDecl: topLevelDecl, - SEMICOLON: semicolonTok, - } - if last2 != nil { - last2.List = next - } - if list2 == nil { - list2 = next - } - last2 = next - goto _2 - } - _3: - } - } - return &SourceFileNode{ - PackageClause: packageClause, - SEMICOLON: semicolonTok, - ImportDeclList: list, - TopLevelDeclList: list2, - } -} - -func (p *parser) statement() Node { - var ( - declaration Node - labeledStmt *LabeledStmtNode - goStmt *GoStmtNode - returnStmt *ReturnStmtNode - breakStmt *BreakStmtNode - continueStmt *ContinueStmtNode - gotoStmt *GotoStmtNode - fallthroughStmt *FallthroughStmtNode - block *BlockNode - ifStmt Node - switchStmt *SwitchStmtNode - selectStmt *SelectStmtNode - forStmt *ForStmtNode - deferStmt *DeferStmtNode - simpleStmt Node - ) - // ebnf.Alternative Declaration | LabeledStmt | GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | DeferStmt | SimpleStmt ctx [ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */] - switch p.c() { - case CONST, TYPE, VAR: // 0 - // *ebnf.Name Declaration ctx [CONST, TYPE, VAR] - if declaration = p.declaration(); declaration == nil { - return nil - } - return declaration - case IDENT: // 1 14 - // *ebnf.Name LabeledStmt ctx [IDENT] - if labeledStmt = p.labeledStmt(); labeledStmt == nil { - goto _2 - } - return labeledStmt - _2: - labeledStmt = nil - // *ebnf.Name SimpleStmt ctx [IDENT] - if simpleStmt = p.simpleStmt(false); simpleStmt == nil { - return nil - } - return simpleStmt - case GO: // 2 - // *ebnf.Name GoStmt ctx [GO] - if goStmt = p.goStmt(); goStmt == nil { - return nil - } - return goStmt - case RETURN: // 3 - // *ebnf.Name ReturnStmt ctx [RETURN] - if returnStmt = p.returnStmt(); returnStmt == nil { - return nil - } - return returnStmt - case BREAK: // 4 - // *ebnf.Name BreakStmt ctx [BREAK] - if breakStmt = p.breakStmt(); breakStmt == nil { - return nil - } - return breakStmt - case CONTINUE: // 5 - // *ebnf.Name ContinueStmt ctx [CONTINUE] - if continueStmt = p.continueStmt(); continueStmt == nil { - return nil - } - return continueStmt - case GOTO: // 6 - // *ebnf.Name GotoStmt ctx [GOTO] - if gotoStmt = p.gotoStmt(); gotoStmt == nil { - return nil - } - return gotoStmt - case FALLTHROUGH: // 7 - // *ebnf.Name FallthroughStmt ctx [FALLTHROUGH] - if fallthroughStmt = p.fallthroughStmt(); fallthroughStmt == nil { - return nil - } - return fallthroughStmt - case LBRACE: // 8 - // *ebnf.Name Block ctx [LBRACE] - if block = p.block(nil, nil); block == nil { - return nil - } - return block - return nil - case IF: // 9 - // *ebnf.Name IfStmt ctx [IF] - if ifStmt = p.ifStmt(); ifStmt == nil { - return nil - } - return ifStmt - case SWITCH: // 10 - // *ebnf.Name SwitchStmt ctx [SWITCH] - if switchStmt = p.switchStmt(); switchStmt == nil { - return nil - } - return switchStmt - case SELECT: // 11 - // *ebnf.Name SelectStmt ctx [SELECT] - if selectStmt = p.selectStmt(); selectStmt == nil { - return nil - } - return selectStmt - case FOR: // 12 - // *ebnf.Name ForStmt ctx [FOR] - if forStmt = p.forStmt(); forStmt == nil { - return nil - } - return forStmt - case DEFER: // 13 - // *ebnf.Name DeferStmt ctx [DEFER] - if deferStmt = p.deferStmt(); deferStmt == nil { - return nil - } - return deferStmt - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */ : // 14 - // *ebnf.Name SimpleStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR /* ε */] - if simpleStmt = p.simpleStmt(false); simpleStmt == nil { - return nil - } - return simpleStmt - } - return nil -} - -// StatementListNode represents the production -// -// StatementList = { Statement ";" } . -type StatementListNode struct { - Statement Node - SEMICOLON Token - List *StatementListNode -} - -// Source implements Node. -func (n *StatementListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *StatementListNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) statementList() *StatementListNode { - var ( - statement Node - list, last *StatementListNode - ) - for { - ix := p.ix - switch p.c() { - case ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */ : - if statement = p.statement(); statement == nil { - p.back(ix) - goto _1 - } - case SEMICOLON: - next := &StatementListNode{ - SEMICOLON: p.consume(), - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - continue - default: - goto _1 - } - - if p.c() != SEMICOLON { - next := &StatementListNode{ - Statement: statement, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _1 - } - next := &StatementListNode{ - Statement: statement, - SEMICOLON: p.consume(), - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - } -_1: - return list -} - -// FieldDeclListNode represents the production -// -// FieldDeclListNode = { FieldDecl ";" } . -type FieldDeclListNode struct { - FieldDecl *FieldDeclNode - SEMICOLON Token - List *FieldDeclListNode -} - -// Source implements Node. -func (n *FieldDeclListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *FieldDeclListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.FieldDecl.Position() -} - -// StructTypeNode represents the production -// -// StructType = "struct" "{" { FieldDecl ";" } "}" . -type StructTypeNode struct { - STRUCT Token - LBRACE Token - FieldDeclList *FieldDeclListNode - RBRACE Token - fields []Field - - guard -} - -// Source implements Node. -func (n *StructTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *StructTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.STRUCT.Position() -} - -func (p *parser) structType() *StructTypeNode { - var ( - ok bool - structTok Token - lbraceTok Token - list, last *FieldDeclListNode - rbraceTok Token - ) - // ebnf.Sequence "struct" "{" { FieldDecl ";" } [ FieldDecl ] "}" ctx [STRUCT] - { - if p.peek(1) != LBRACE { - return nil - } - ix := p.ix - // *ebnf.Token "struct" ctx [STRUCT] - structTok = p.expect(STRUCT) - // *ebnf.Token "{" ctx [LBRACE] - lbraceTok = p.expect(LBRACE) - // *ebnf.Repetition { FieldDecl ";" } ctx [] - _0: - { - var fieldDecl *FieldDeclNode - var semicolonTok Token - switch p.c() { - case IDENT, MUL: - // ebnf.Sequence FieldDecl ";" ctx [IDENT, MUL] - ix := p.ix - // *ebnf.Name FieldDecl ctx [IDENT, MUL] - if fieldDecl = p.fieldDecl(); fieldDecl == nil { - p.back(ix) - goto _1 - } - if p.c() == RBRACE { - next := &FieldDeclListNode{ - FieldDecl: fieldDecl, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _1 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _1 - } - next := &FieldDeclListNode{ - FieldDecl: fieldDecl, - SEMICOLON: semicolonTok, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _0 - } - _1: - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - return nil - } - } - return &StructTypeNode{ - STRUCT: structTok, - LBRACE: lbraceTok, - FieldDeclList: list, - RBRACE: rbraceTok, - } -} - -// SwitchStmtNode represents the production -// -// SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . -type SwitchStmtNode struct { - ExprSwitchStmt *ExprSwitchStmtNode - TypeSwitchStmt *TypeSwitchStmtNode -} - -// Source implements Node. -func (n *SwitchStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *SwitchStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) switchStmt() *SwitchStmtNode { - var ( - exprSwitchStmt *ExprSwitchStmtNode - typeSwitchStmt *TypeSwitchStmtNode - ) - p.openScope() - - defer p.closeScope() - - // ebnf.Alternative ExprSwitchStmt | TypeSwitchStmt ctx [SWITCH] - switch p.c() { - case SWITCH: // 0 1 - // *ebnf.Name ExprSwitchStmt ctx [SWITCH] - if exprSwitchStmt = p.exprSwitchStmt(); exprSwitchStmt == nil { - goto _0 - } - break - _0: - exprSwitchStmt = nil - p.closeScope() - p.openScope() - // *ebnf.Name TypeSwitchStmt ctx [SWITCH] - if typeSwitchStmt = p.typeSwitchStmt(); typeSwitchStmt == nil { - goto _1 - } - break - _1: - typeSwitchStmt = nil - return nil - default: - return nil - } - return &SwitchStmtNode{ - ExprSwitchStmt: exprSwitchStmt, - TypeSwitchStmt: typeSwitchStmt, - } -} - -// TagNode represents the production -// -// Tag = string_lit . -type TagNode struct { - STRING Token -} - -// Source implements Node. -func (n *TagNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TagNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.STRING.Position() -} - -func (p *parser) tag() *TagNode { - var ( - stringTok Token - ) - // *ebnf.Name string_lit ctx [STRING] - stringTok = p.expect(STRING) - return &TagNode{ - STRING: stringTok, - } -} - -func (p *parser) topLevelDecl() (r Node) { - // ebnf.Alternative Declaration | FunctionDecl | MethodDecl ctx [CONST, FUNC, TYPE, VAR] - switch p.c() { - case CONST, TYPE, VAR: // 0 - // *ebnf.Name Declaration ctx [CONST, TYPE, VAR] - return p.declaration() - case FUNC: // 1 2 - // *ebnf.Name FunctionDecl ctx [FUNC] - if functionDecl := p.functionDecl(); functionDecl != nil { - return functionDecl - } - // *ebnf.Name MethodDecl ctx [FUNC] - return p.methodDecl() - } - return nil -} - -// TypeNode represents the production -// -// Type = TypeName TypeArgs . -type TypeNode struct { - TypeName *TypeNameNode - TypeArgs *TypeArgsNode -} - -// Source implements Node. -func (n *TypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.TypeName != nil { - return n.TypeName.Position() - } - - return r -} - -// ParenthesizedTypeNode represents the production -// -// ParenthesizedType = "(" Type ")" . -type ParenthesizedTypeNode struct { - LPAREN Token - TypeNode Type - RPAREN Token -} - -// Source implements Node. -func (n *ParenthesizedTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *ParenthesizedTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.LPAREN.IsValid() { - return n.LPAREN.Position() - } - - return r -} - -func (p *parser) type1() Type { - var ( - ok bool - typeName *TypeNameNode - typeArgs *TypeArgsNode - typeLit Type - lparenTok Token - typeNode Type - rparenTok Token - ) - // ebnf.Alternative TypeName [ TypeArgs ] | TypeLit | "(" Type ")" ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - switch p.c() { - case IDENT: // 0 - // ebnf.Sequence TypeName [ TypeArgs ] ctx [IDENT] - { - ix := p.ix - // *ebnf.Name TypeName ctx [IDENT] - if typeName = p.typeName(); typeName == nil { - p.back(ix) - goto _0 - } - // *ebnf.Option [ TypeArgs ] ctx [] - switch p.c() { - case LBRACK: - // *ebnf.Name TypeArgs ctx [LBRACK] - if typeArgs = p.typeArgs(); typeArgs == nil { - goto _2 - } - } - goto _3 - _2: - typeArgs = nil - _3: - } - if typeArgs == nil { - return typeName - } - - break - _0: - typeArgs = nil - typeName = nil - return nil - case ARROW, CHAN, FUNC, INTERFACE, LBRACK, MAP, MUL, STRUCT: // 1 - // *ebnf.Name TypeLit ctx [ARROW, CHAN, FUNC, INTERFACE, LBRACK, MAP, MUL, STRUCT] - if typeLit = p.typeLit(); typeLit == nil { - goto _4 - } - return typeLit - _4: - typeLit = nil - return nil - case LPAREN: // 2 - // ebnf.Sequence "(" Type ")" ctx [LPAREN] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - goto _6 - } - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _6 - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - goto _6 - } - } - return &ParenthesizedTypeNode{LPAREN: lparenTok, TypeNode: typeNode, RPAREN: rparenTok} - _6: - lparenTok = Token{} - rparenTok = Token{} - typeNode = nil - return nil - default: - return nil - } - return &TypeNode{ - TypeName: typeName, - TypeArgs: typeArgs, - } -} - -// TypeArgsNode represents the production -// -// TypeArgs = "[" TypeList [ "," ] "]" . -type TypeArgsNode struct { - LBRACK Token - TypeList *TypeListNode - COMMA Token - RBRACK Token -} - -// Source implements Node. -func (n *TypeArgsNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeArgsNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACK.Position() -} - -func (p *parser) typeArgs() *TypeArgsNode { - var ( - ok bool - lbrackTok Token - typeList *TypeListNode - commaTok Token - rbrackTok Token - ) - // ebnf.Sequence "[" TypeList [ "," ] "]" ctx [LBRACK] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - return nil - } - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Name TypeList ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeList = p.typeList(); typeList == nil { - p.back(ix) - return nil - } - // *ebnf.Option [ "," ] ctx [] - switch p.c() { - case COMMA: - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - } - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - return nil - } - } - return &TypeArgsNode{ - LBRACK: lbrackTok, - TypeList: typeList, - COMMA: commaTok, - RBRACK: rbrackTok, - } -} - -// TypeAssertionNode represents the production -// -// TypeAssertion = "." "(" Type ")" . -type TypeAssertionNode struct { - PERIOD Token - LPAREN Token - TypeNode Type - RPAREN Token -} - -// Source implements Node. -func (n *TypeAssertionNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeAssertionNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.PERIOD.Position() -} - -func (p *parser) typeAssertion() *TypeAssertionNode { - var ( - ok bool - periodTok Token - lparenTok Token - typeNode Type - rparenTok Token - ) - // ebnf.Sequence "." "(" Type ")" ctx [PERIOD] - { - if p.peek(1) != LPAREN { - return nil - } - ix := p.ix - // *ebnf.Token "." ctx [PERIOD] - periodTok = p.expect(PERIOD) - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Name Type ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - return nil - } - } - return &TypeAssertionNode{ - PERIOD: periodTok, - LPAREN: lparenTok, - TypeNode: typeNode, - RPAREN: rparenTok, - } -} - -// TypeCaseClauseNode represents the production -// -// TypeCaseClause = TypeSwitchCase ":" StatementList . -type TypeCaseClauseNode struct { - TypeSwitchCase *TypeSwitchCaseNode - COLON Token - StatementList *StatementListNode -} - -// Source implements Node. -func (n *TypeCaseClauseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeCaseClauseNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TypeSwitchCase.Position() -} - -func (p *parser) typeCaseClause() *TypeCaseClauseNode { - var ( - ok bool - typeSwitchCase *TypeSwitchCaseNode - colonTok Token - statementList *StatementListNode - ) - // ebnf.Sequence TypeSwitchCase ":" StatementList ctx [CASE, DEFAULT] - { - p.openScope() - - defer p.closeScope() - - ix := p.ix - // *ebnf.Name TypeSwitchCase ctx [CASE, DEFAULT] - if typeSwitchCase = p.typeSwitchCase(); typeSwitchCase == nil { - p.back(ix) - return nil - } - // *ebnf.Token ":" ctx [] - if colonTok, ok = p.accept(COLON); !ok { - p.back(ix) - return nil - } - // *ebnf.Name StatementList ctx [] - switch p.c() { - case ADD, AND, ARROW, BREAK, CHAN, CHAR, CONST, CONTINUE, DEFER, FALLTHROUGH, FLOAT, FOR, FUNC, GO, GOTO, IDENT, IF, IMAG, INT, INTERFACE, LBRACE, LBRACK, LPAREN, MAP, MUL, NOT, RETURN, SELECT, SEMICOLON, STRING, STRUCT, SUB, SWITCH, TYPE, VAR, XOR /* ε */ : - if statementList = p.statementList(); statementList == nil { - p.back(ix) - return nil - } - } - } - return &TypeCaseClauseNode{ - TypeSwitchCase: typeSwitchCase, - COLON: colonTok, - StatementList: statementList, - } -} - -// TypeConstraintNode represents the production -// -// TypeConstraint = TypeElem . -type TypeConstraintNode struct { - TypeElem *TypeElemListNode -} - -// Source implements Node. -func (n *TypeConstraintNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeConstraintNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TypeElem.Position() -} - -func (p *parser) typeConstraint() *TypeConstraintNode { - var ( - typeElem *TypeElemListNode - ) - // *ebnf.Name TypeElem ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - if typeElem = p.typeElem(); typeElem == nil { - return nil - } - return &TypeConstraintNode{ - TypeElem: typeElem, - } -} - -// TypeSpecListNode represents the production -// -// TypeSpecListNode = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . -type TypeSpecListNode struct { - TypeSpec Node - SEMICOLON Token - List *TypeSpecListNode -} - -// Source implements Node. -func (n *TypeSpecListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeSpecListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TypeSpec.Position() -} - -// TypeDeclNode represents the production -// -// TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . -type TypeDeclNode struct { - TYPE Token - LPAREN Token - TypeSpecList *TypeSpecListNode - RPAREN Token -} - -// Source implements Node. -func (n *TypeDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TYPE.Position() -} - -func (p *parser) typeDecl() *TypeDeclNode { - var ( - ok bool - typeTok Token - typeSpec Node - lparenTok Token - list, last *TypeSpecListNode - rparenTok Token - ) - // ebnf.Sequence "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) ctx [TYPE] - { - switch p.peek(1) { - case IDENT, LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Token "type" ctx [TYPE] - typeTok = p.expect(TYPE) - // *ebnf.Group ( TypeSpec | "(" { TypeSpec ";" } ")" ) ctx [IDENT, LPAREN] - // ebnf.Alternative TypeSpec | "(" { TypeSpec ";" } ")" ctx [IDENT, LPAREN] - switch p.c() { - case IDENT: // 0 - // *ebnf.Name TypeSpec ctx [IDENT] - if typeSpec = p.typeSpec(); typeSpec == nil { - goto _0 - } - list = &TypeSpecListNode{ - TypeSpec: typeSpec, - } - break - _0: - typeSpec = nil - p.back(ix) - return nil - case LPAREN: // 1 - // ebnf.Sequence "(" { TypeSpec ";" } ")" ctx [LPAREN] - { - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Repetition { TypeSpec ";" } ctx [] - _4: - { - var typeSpec Node - var semicolonTok Token - switch p.c() { - case IDENT: - // ebnf.Sequence TypeSpec ";" ctx [IDENT] - ix := p.ix - // *ebnf.Name TypeSpec ctx [IDENT] - if typeSpec = p.typeSpec(); typeSpec == nil { - p.back(ix) - goto _5 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _5 - } - next := &TypeSpecListNode{ - TypeSpec: typeSpec, - SEMICOLON: semicolonTok, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _4 - } - _5: - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - goto _2 - } - } - break - _2: - lparenTok = Token{} - rparenTok = Token{} - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - } - return &TypeDeclNode{ - TYPE: typeTok, - LPAREN: lparenTok, - TypeSpecList: list, - RPAREN: rparenTok, - } -} - -// TypeDefNode represents the production -// -// TypeDef = identifier [ TypeParameters ] Type . -type TypeDefNode struct { - IDENT Token - TypeParameters *TypeParametersNode - TypeNode Type - - pkg *Package - visible -} - -// Source implements Node. -func (n *TypeDefNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeDefNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IDENT.Position() -} - -func (p *parser) typeDef() (r *TypeDefNode) { - var ( - identTok Token - typeParameters *TypeParametersNode - typeNode Type - ) - // ebnf.Sequence identifier [ TypeParameters ] Type ctx [IDENT] - { - ix := p.ix - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - // *ebnf.Option [ TypeParameters ] ctx [] - switch p.c() { - case LBRACK: - // *ebnf.Name TypeParameters ctx [LBRACK] - if typeParameters = p.typeParameters(); typeParameters == nil { - goto _0 - } - } - goto _1 - _0: - typeParameters = nil - _1: - // *ebnf.Name Type ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - r = &TypeDefNode{ - IDENT: identTok, - TypeParameters: typeParameters, - TypeNode: typeNode, - } - p.declare(p.sc, identTok, r, int32(p.ix), false) - return r -} - -// TypeElemListNode represents the production -// -// TypeElem = TypeTerm { "|" TypeTerm } . -type TypeElemListNode struct { - OR Token - TypeTerm *TypeTermNode - List *TypeElemListNode -} - -// Source implements Node. -func (n *TypeElemListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeElemListNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.OR.IsValid() { - return n.OR.Position() - } - - return n.TypeTerm.Position() -} - -func (p *parser) typeElem() *TypeElemListNode { - var ( - typeTerm *TypeTermNode - list, last *TypeElemListNode - ) - // ebnf.Sequence TypeTerm { "|" TypeTerm } ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - { - ix := p.ix - // *ebnf.Name TypeTerm ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - if typeTerm = p.typeTerm(); typeTerm == nil { - p.back(ix) - return nil - } - list = &TypeElemListNode{ - TypeTerm: typeTerm, - } - last = list - // *ebnf.Repetition { "|" TypeTerm } ctx [] - _0: - { - var orTok Token - var typeTerm *TypeTermNode - switch p.c() { - case OR: - // ebnf.Sequence "|" TypeTerm ctx [OR] - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "|" ctx [OR] - orTok = p.expect(OR) - // *ebnf.Name TypeTerm ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - if typeTerm = p.typeTerm(); typeTerm == nil { - p.back(ix) - goto _1 - } - next := &TypeElemListNode{ - OR: orTok, - TypeTerm: typeTerm, - } - last.List = next - last = next - goto _0 - } - _1: - } - } - return list -} - -// TypeListNode represents the production -// -// TypeList = Type { "," Type } . -type TypeListNode struct { - COMMA Token - TypeNode Type - List *TypeListNode -} - -// Source implements Node. -func (n *TypeListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeListNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.COMMA.IsValid() { - return n.COMMA.Position() - } - - return n.TypeNode.Position() -} - -func (p *parser) typeList() *TypeListNode { - var ( - typeNode Type - list, last *TypeListNode - ) - // ebnf.Sequence Type { "," Type } ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - return nil - } - list = &TypeListNode{ - TypeNode: typeNode, - } - last = list - // *ebnf.Repetition { "," Type } ctx [] - _0: - { - var commaTok Token - var typeNode Type - switch p.c() { - case COMMA: - // ebnf.Sequence "," Type ctx [COMMA] - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _1 - } - next := &TypeListNode{ - COMMA: commaTok, - TypeNode: typeNode, - } - last.List = next - last = next - goto _0 - } - _1: - } - } - return list -} - -func (p *parser) typeLit() Type { - var ( - arrayType *ArrayTypeNode - structType *StructTypeNode - pointerType *PointerTypeNode - functionType *FunctionTypeNode - interfaceType *InterfaceTypeNode - mapType *MapTypeNode - channelType *ChannelTypeNode - ) - // ebnf.Alternative ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType ctx [ARROW, CHAN, FUNC, INTERFACE, LBRACK, MAP, MUL, STRUCT] - switch p.c() { - case LBRACK: // 0 5 - if p.peek(1) == RBRACK { - return p.sliceType() - } - - // *ebnf.Name ArrayType ctx [LBRACK] - if arrayType = p.arrayType(); arrayType != nil { - return arrayType - } - case STRUCT: // 1 - // *ebnf.Name StructType ctx [STRUCT] - if structType = p.structType(); structType != nil { - return structType - } - case MUL: // 2 - // *ebnf.Name PointerType ctx [MUL] - if pointerType = p.pointerType(); pointerType != nil { - return pointerType - } - case FUNC: // 3 - // *ebnf.Name FunctionType ctx [FUNC] - if functionType = p.functionType(); functionType != nil { - return functionType - } - case INTERFACE: // 4 - // *ebnf.Name InterfaceType ctx [INTERFACE] - if interfaceType = p.interfaceType(); interfaceType != nil { - return interfaceType - } - case MAP: // 6 - // *ebnf.Name MapType ctx [MAP] - if mapType = p.mapType(); mapType != nil { - return mapType - } - case ARROW, CHAN: // 7 - // *ebnf.Name ChannelType ctx [ARROW, CHAN] - if channelType = p.channelType(); channelType != nil { - return channelType - } - } - return nil -} - -// TypeNameNode represents the production -// -// TypeName = QualifiedIdent | identifier . -type TypeNameNode struct { - Name Node - lexicalScoper -} - -// Source implements Node. -func (n *TypeNameNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeNameNode) Position() (r token.Position) { - if n == nil || n.Name == nil { - return r - } - - return n.Name.Position() -} - -func (p *parser) typeName() *TypeNameNode { - var ( - qualifiedIdent *QualifiedIdentNode - ) - // ebnf.Alternative QualifiedIdent | identifier ctx [IDENT] - switch p.c() { - case IDENT: // 0 1 - // *ebnf.Name QualifiedIdent ctx [IDENT] - if qualifiedIdent = p.qualifiedIdent(); qualifiedIdent != nil { - return &TypeNameNode{ - Name: qualifiedIdent, - lexicalScoper: newLexicalScoper(p.sc), - } - } - - // *ebnf.Name identifier ctx [IDENT] - return &TypeNameNode{ - Name: p.expect(IDENT), - lexicalScoper: newLexicalScoper(p.sc), - } - default: - return nil - } -} - -// TypeParamDeclNode represents the production -// -// TypeParamDecl = IdentifierList TypeConstraint . -type TypeParamDeclNode struct { - IdentifierList *IdentifierListNode - TypeConstraint *TypeConstraintNode -} - -// Source implements Node. -func (n *TypeParamDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeParamDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IdentifierList.Position() -} - -func (p *parser) typeParamDecl() *TypeParamDeclNode { - var ( - identifierList *IdentifierListNode - typeConstraint *TypeConstraintNode - ) - // ebnf.Sequence IdentifierList TypeConstraint ctx [IDENT] - { - ix := p.ix - // *ebnf.Name IdentifierList ctx [IDENT] - if identifierList = p.identifierList(); identifierList == nil { - p.back(ix) - return nil - } - // *ebnf.Name TypeConstraint ctx [] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE: - if typeConstraint = p.typeConstraint(); typeConstraint == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - } - return &TypeParamDeclNode{ - IdentifierList: identifierList, - TypeConstraint: typeConstraint, - } -} - -// TypeParamListNode represents the production -// -// TypeParamList = TypeParamDecl { "," TypeParamDecl } . -type TypeParamListNode struct { - COMMA Token - TypeParamDecl *TypeParamDeclNode - List *TypeParamListNode -} - -// Source implements Node. -func (n *TypeParamListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeParamListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TypeParamDecl.Position() -} - -func (p *parser) typeParamList() *TypeParamListNode { - var ( - typeParamDecl *TypeParamDeclNode - list, last *TypeParamListNode - ) - // ebnf.Sequence TypeParamDecl { "," TypeParamDecl } ctx [IDENT] - { - ix := p.ix - // *ebnf.Name TypeParamDecl ctx [IDENT] - if typeParamDecl = p.typeParamDecl(); typeParamDecl == nil { - p.back(ix) - return nil - } - list = &TypeParamListNode{ - TypeParamDecl: typeParamDecl, - } - last = list - // *ebnf.Repetition { "," TypeParamDecl } ctx [] - _0: - { - var commaTok Token - var typeParamDecl *TypeParamDeclNode - switch p.c() { - case COMMA: - // ebnf.Sequence "," TypeParamDecl ctx [COMMA] - switch p.peek(1) { - case IDENT: - default: - goto _1 - } - ix := p.ix - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - // *ebnf.Name TypeParamDecl ctx [IDENT] - if typeParamDecl = p.typeParamDecl(); typeParamDecl == nil { - p.back(ix) - goto _1 - } - next := &TypeParamListNode{ - COMMA: commaTok, - TypeParamDecl: typeParamDecl, - } - last.List = next - last = next - goto _0 - } - _1: - } - } - return list -} - -// TypeParametersNode represents the production -// -// TypeParameters = "[" TypeParamList [ "," ] "]" . -type TypeParametersNode struct { - LBRACK Token - TypeParamList *TypeParamListNode - COMMA Token - RBRACK Token -} - -// Source implements Node. -func (n *TypeParametersNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeParametersNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.LBRACK.Position() -} - -func (p *parser) typeParameters() *TypeParametersNode { - var ( - ok bool - lbrackTok Token - typeParamList *TypeParamListNode - commaTok Token - rbrackTok Token - ) - // ebnf.Sequence "[" TypeParamList [ "," ] "]" ctx [LBRACK] - { - switch p.peek(1) { - case IDENT: - default: - return nil - } - ix := p.ix - // *ebnf.Token "[" ctx [LBRACK] - lbrackTok = p.expect(LBRACK) - // *ebnf.Name TypeParamList ctx [IDENT] - if typeParamList = p.typeParamList(); typeParamList == nil { - p.back(ix) - return nil - } - // *ebnf.Option [ "," ] ctx [] - switch p.c() { - case COMMA: - // *ebnf.Token "," ctx [COMMA] - commaTok = p.expect(COMMA) - } - // *ebnf.Token "]" ctx [] - if rbrackTok, ok = p.accept(RBRACK); !ok { - p.back(ix) - return nil - } - } - return &TypeParametersNode{ - LBRACK: lbrackTok, - TypeParamList: typeParamList, - COMMA: commaTok, - RBRACK: rbrackTok, - } -} - -func (p *parser) typeSpec() Node { - var ( - aliasDecl *AliasDeclNode - typeDef *TypeDefNode - ) - // ebnf.Alternative AliasDecl | TypeDef ctx [IDENT] - switch p.c() { - case IDENT: // 0 1 - // *ebnf.Name AliasDecl ctx [IDENT] - if aliasDecl = p.aliasDecl(); aliasDecl == nil { - goto _0 - } - return aliasDecl - _0: - aliasDecl = nil - // *ebnf.Name TypeDef ctx [IDENT] - if typeDef = p.typeDef(); typeDef == nil { - return nil - } - return typeDef - default: - return nil - } -} - -// TypeSwitchCaseNode represents the production -// -// TypeSwitchCase = "case" TypeList | "default" . -type TypeSwitchCaseNode struct { - CASE Token - TypeList *TypeListNode - DEFAULT Token -} - -// Source implements Node. -func (n *TypeSwitchCaseNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeSwitchCaseNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) typeSwitchCase() *TypeSwitchCaseNode { - var ( - caseTok Token - typeList *TypeListNode - defaultTok Token - ) - // ebnf.Alternative "case" TypeList | "default" ctx [CASE, DEFAULT] - switch p.c() { - case CASE: // 0 - // ebnf.Sequence "case" TypeList ctx [CASE] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - goto _0 - } - ix := p.ix - // *ebnf.Token "case" ctx [CASE] - caseTok = p.expect(CASE) - // *ebnf.Name TypeList ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeList = p.typeList(); typeList == nil { - p.back(ix) - goto _0 - } - } - break - _0: - caseTok = Token{} - typeList = nil - return nil - case DEFAULT: // 1 - // *ebnf.Token "default" ctx [DEFAULT] - defaultTok = p.expect(DEFAULT) - default: - return nil - } - return &TypeSwitchCaseNode{ - CASE: caseTok, - TypeList: typeList, - DEFAULT: defaultTok, - } -} - -// TypeSwitchGuardNode represents the production -// -// TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . -type TypeSwitchGuardNode struct { - IDENT Token - DEFINE Token - PrimaryExpr Expression - PERIOD Token - LPAREN Token - TYPE Token - RPAREN Token -} - -// Source implements Node. -func (n *TypeSwitchGuardNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeSwitchGuardNode) Position() (r token.Position) { - if n == nil { - return r - } - - panic("TODO") -} - -func (p *parser) typeSwitchGuard() *TypeSwitchGuardNode { - var ( - ok bool - identTok Token - defineTok Token - primaryExpr Expression - periodTok Token - lparenTok Token - typeTok Token - rparenTok Token - ) - // ebnf.Sequence [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" ctx [ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT] - { - ix := p.ix - // *ebnf.Option [ identifier ":=" ] ctx [ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT] - switch p.c() { - case IDENT: - // ebnf.Sequence identifier ":=" ctx [IDENT] - { - if p.peek(1) != DEFINE { - goto _0 - } - // *ebnf.Name identifier ctx [IDENT] - identTok = p.expect(IDENT) - // *ebnf.Token ":=" ctx [DEFINE] - defineTok = p.expect(DEFINE) - } - } - goto _1 - _0: - defineTok = Token{} - identTok = Token{} - _1: - // *ebnf.Name PrimaryExpr ctx [] - switch p.c() { - case ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT: - if primaryExpr = p.primaryExpr(false); primaryExpr == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Token "." ctx [] - if periodTok, ok = p.accept(PERIOD); !ok { - p.back(ix) - return nil - } - // *ebnf.Token "(" ctx [] - if lparenTok, ok = p.accept(LPAREN); !ok { - p.back(ix) - return nil - } - // *ebnf.Token "type" ctx [] - if typeTok, ok = p.accept(TYPE); !ok { - p.back(ix) - return nil - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - return nil - } - } - return &TypeSwitchGuardNode{ - IDENT: identTok, - DEFINE: defineTok, - PrimaryExpr: primaryExpr, - PERIOD: periodTok, - LPAREN: lparenTok, - TYPE: typeTok, - RPAREN: rparenTok, - } -} - -// TypeCaseClauseListNode represents the production -// -// TypeCaseClauseListNode = { TypeCaseClause } . -type TypeCaseClauseListNode struct { - TypeCaseClause *TypeCaseClauseNode - List *TypeCaseClauseListNode -} - -// Source implements Node. -func (n *TypeCaseClauseListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeCaseClauseListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TypeCaseClause.Position() -} - -// TypeSwitchStmtNode represents the production -// -// TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . -type TypeSwitchStmtNode struct { - SWITCH Token - SimpleStmt Node - SEMICOLON Token - TypeSwitchGuard *TypeSwitchGuardNode - LBRACE Token - TypeCaseClauseList *TypeCaseClauseListNode - RBRACE Token -} - -// Source implements Node. -func (n *TypeSwitchStmtNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeSwitchStmtNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.SWITCH.Position() -} - -func (p *parser) typeSwitchStmt() *TypeSwitchStmtNode { - var ( - ok bool - switchTok Token - simpleStmt Node - semicolonTok Token - typeSwitchGuard *TypeSwitchGuardNode - lbraceTok Token - list, last *TypeCaseClauseListNode - rbraceTok Token - ) - // ebnf.Sequence "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" ctx [SWITCH] - { - ix := p.ix - // *ebnf.Token "switch" ctx [SWITCH] - switchTok = p.expect(SWITCH) - // *ebnf.Option [ SimpleStmt ";" ] ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, SEMICOLON, STRING, STRUCT, SUB, XOR: - // ebnf.Sequence SimpleStmt ";" ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, SEMICOLON, STRING, STRUCT, SUB, XOR] - { - ix := p.ix - // *ebnf.Name SimpleStmt ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, SEMICOLON, STRING, STRUCT, SUB, XOR] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if simpleStmt = p.simpleStmt(false); simpleStmt == nil { - p.back(ix) - goto _0 - } - default: - p.back(ix) - goto _0 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _0 - } - } - } - goto _1 - _0: - semicolonTok = Token{} - simpleStmt = nil - _1: - // *ebnf.Name TypeSwitchGuard ctx [] - switch p.c() { - case ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRING, STRUCT: - if typeSwitchGuard = p.typeSwitchGuard(); typeSwitchGuard == nil { - p.back(ix) - return nil - } - default: - p.back(ix) - return nil - } - // *ebnf.Token "{" ctx [] - if lbraceTok, ok = p.accept(LBRACE); !ok { - p.back(ix) - return nil - } - // *ebnf.Repetition { TypeCaseClause } ctx [] - _2: - { - var typeCaseClause *TypeCaseClauseNode - switch p.c() { - case CASE, DEFAULT: - // *ebnf.Name TypeCaseClause ctx [CASE, DEFAULT] - if typeCaseClause = p.typeCaseClause(); typeCaseClause == nil { - goto _3 - } - next := &TypeCaseClauseListNode{ - TypeCaseClause: typeCaseClause, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _2 - } - _3: - } - // *ebnf.Token "}" ctx [] - if rbraceTok, ok = p.accept(RBRACE); !ok { - p.back(ix) - return nil - } - } - return &TypeSwitchStmtNode{ - SWITCH: switchTok, - SimpleStmt: simpleStmt, - SEMICOLON: semicolonTok, - TypeSwitchGuard: typeSwitchGuard, - LBRACE: lbraceTok, - TypeCaseClauseList: list, - RBRACE: rbraceTok, - } -} - -// TypeTermNode represents the production -// -// TypeTerm = Type | UnderlyingType . -type TypeTermNode struct { - TypeNode Type - UnderlyingType *UnderlyingTypeNode -} - -// Source implements Node. -func (n *TypeTermNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *TypeTermNode) Position() (r token.Position) { - if n == nil { - return r - } - - if n.TypeNode != nil { - return n.TypeNode.Position() - } - - return n.UnderlyingType.Position() -} - -func (p *parser) typeTerm() *TypeTermNode { - var ( - typeNode Type - underlyingType *UnderlyingTypeNode - ) - // ebnf.Alternative Type | UnderlyingType ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT, TILDE] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: // 0 - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - goto _0 - } - break - _0: - typeNode = nil - return nil - case TILDE: // 1 - // *ebnf.Name UnderlyingType ctx [TILDE] - if underlyingType = p.underlyingType(); underlyingType == nil { - goto _2 - } - break - _2: - underlyingType = nil - return nil - default: - return nil - } - return &TypeTermNode{ - TypeNode: typeNode, - UnderlyingType: underlyingType, - } -} - -// UnaryExprNode represents the production -// -// UnaryExpr = PrimaryExpr | ( "+" | "-" | "!" | "^" | "*" | "&" | "<-" ) UnaryExpr . -type UnaryExprNode struct { - Op Token - UnaryExpr Expression - - typeCache - valueCache -} - -// Source implements Node. -func (n *UnaryExprNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *UnaryExprNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.Op.Position() -} - -func (p *parser) unaryExpr(preBlock bool) Expression { - var ( - primaryExpr Expression - op Token - unaryExpr Expression - ) - // ebnf.Alternative PrimaryExpr | ( "+" | "-" | "!" | "^" | "*" | "&" | "<-" ) UnaryExpr ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - switch p.c() { - case CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, STRING, STRUCT: // 0 - // *ebnf.Name PrimaryExpr ctx [CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, STRING, STRUCT] - if primaryExpr = p.primaryExpr(preBlock); primaryExpr == nil { - return nil - } - return primaryExpr - case ARROW, MUL: // 0 1 - // *ebnf.Name PrimaryExpr ctx [ARROW, MUL] - if primaryExpr = p.primaryExpr(preBlock); primaryExpr == nil { - goto _2 - } - return primaryExpr - _2: - primaryExpr = nil - // ebnf.Sequence ( "+" | "-" | "!" | "^" | "*" | "&" | "<-" ) UnaryExpr ctx [ARROW, MUL] - { - ix := p.ix - // *ebnf.Group ( "+" | "-" | "!" | "^" | "*" | "&" | "<-" ) ctx [ARROW, MUL] - // ebnf.Alternative "+" | "-" | "!" | "^" | "*" | "&" | "<-" ctx [ARROW, MUL] - op = p.consume() - // *ebnf.Name UnaryExpr ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if unaryExpr = p.unaryExpr(preBlock); unaryExpr == nil { - p.back(ix) - goto _3 - } - default: - p.back(ix) - goto _3 - } - } - break - _3: - unaryExpr = nil - return nil - case ADD, AND, NOT, SUB, XOR: // 1 - // ebnf.Sequence ( "+" | "-" | "!" | "^" | "*" | "&" | "<-" ) UnaryExpr ctx [ADD, AND, NOT, SUB, XOR] - { - ix := p.ix - // *ebnf.Group ( "+" | "-" | "!" | "^" | "*" | "&" | "<-" ) ctx [ADD, AND, NOT, SUB, XOR] - // ebnf.Alternative "+" | "-" | "!" | "^" | "*" | "&" | "<-" ctx [ADD, AND, NOT, SUB, XOR] - op = p.consume() - // *ebnf.Name UnaryExpr ctx [] - switch p.c() { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - if unaryExpr = p.unaryExpr(preBlock); unaryExpr == nil { - p.back(ix) - goto _8 - } - default: - p.back(ix) - goto _8 - } - } - break - _8: - op = Token{} - unaryExpr = nil - return nil - default: - return nil - } - return &UnaryExprNode{ - Op: op, - UnaryExpr: unaryExpr, - } -} - -// UnderlyingTypeNode represents the production -// -// UnderlyingType = "~" Type . -type UnderlyingTypeNode struct { - TILDE Token - TypeNode Type -} - -// Source implements Node. -func (n *UnderlyingTypeNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *UnderlyingTypeNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.TILDE.Position() -} - -func (p *parser) underlyingType() *UnderlyingTypeNode { - var ( - tildeTok Token - typeNode Type - ) - // ebnf.Sequence "~" Type ctx [TILDE] - { - switch p.peek(1) { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: - default: - return nil - } - ix := p.ix - // *ebnf.Token "~" ctx [TILDE] - tildeTok = p.expect(TILDE) - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - return nil - } - } - return &UnderlyingTypeNode{ - TILDE: tildeTok, - TypeNode: typeNode, - } -} - -// VarSpecListNode represents the production -// -// VarSpecListNode = { VarSpec ";" } . -type VarSpecListNode struct { - VarSpec Node - SEMICOLON Token - List *VarSpecListNode -} - -// Source implements Node. -func (n *VarSpecListNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *VarSpecListNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.VarSpec.Position() -} - -// VarDeclNode represents the production -// -// VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) . -type VarDeclNode struct { - VAR Token - LPAREN Token - VarSpec Node - RPAREN Token -} - -// Source implements Node. -func (n *VarDeclNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *VarDeclNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.VAR.Position() -} - -func (p *parser) varDecl() *VarDeclNode { - var ( - ok bool - varTok Token - varSpec Node - lparenTok Token - list, last *VarSpecListNode - rparenTok Token - ) - // ebnf.Sequence "var" ( VarSpec | "(" { VarSpec ";" } ")" ) ctx [VAR] - { - switch p.peek(1) { - case IDENT, LPAREN: - default: - return nil - } - ix := p.ix - // *ebnf.Token "var" ctx [VAR] - varTok = p.expect(VAR) - // *ebnf.Group ( VarSpec | "(" { VarSpec ";" } ")" ) ctx [IDENT, LPAREN] - // ebnf.Alternative VarSpec | "(" { VarSpec ";" } ")" ctx [IDENT, LPAREN] - switch p.c() { - case IDENT: // 0 - // *ebnf.Name VarSpec ctx [IDENT] - if varSpec = p.varSpec(); varSpec == nil { - goto _0 - } - list = &VarSpecListNode{ - VarSpec: varSpec, - } - break - _0: - varSpec = nil - p.back(ix) - return nil - case LPAREN: // 1 - // ebnf.Sequence "(" { VarSpec ";" } ")" ctx [LPAREN] - { - ix := p.ix - // *ebnf.Token "(" ctx [LPAREN] - lparenTok = p.expect(LPAREN) - // *ebnf.Repetition { VarSpec ";" } ctx [] - _4: - { - var varSpec Node - var semicolonTok Token - switch p.c() { - case IDENT: - // ebnf.Sequence VarSpec ";" ctx [IDENT] - ix := p.ix - // *ebnf.Name VarSpec ctx [IDENT] - if varSpec = p.varSpec(); varSpec == nil { - p.back(ix) - goto _5 - } - // *ebnf.Token ";" ctx [] - if semicolonTok, ok = p.accept(SEMICOLON); !ok { - p.back(ix) - goto _5 - } - next := &VarSpecListNode{ - VarSpec: varSpec, - SEMICOLON: semicolonTok, - } - if last != nil { - last.List = next - } - if list == nil { - list = next - } - last = next - goto _4 - } - _5: - } - // *ebnf.Token ")" ctx [] - if rparenTok, ok = p.accept(RPAREN); !ok { - p.back(ix) - goto _2 - } - } - break - _2: - lparenTok = Token{} - rparenTok = Token{} - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - } - if list != nil && list.List == nil && !list.SEMICOLON.IsValid() { - return &VarDeclNode{ - VAR: varTok, - LPAREN: lparenTok, - VarSpec: list.VarSpec, - RPAREN: rparenTok, - } - } - - return &VarDeclNode{ - VAR: varTok, - LPAREN: lparenTok, - VarSpec: list, - RPAREN: rparenTok, - } -} - -// VarSpecNode represents the production -// -// VarSpec = identifier ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . -type VarSpecNode struct { - IDENT Token - TypeNode Type - ASSIGN Token - ExpressionList *ExpressionListNode - lexicalScoper - - visible -} - -// Source implements Node. -func (n *VarSpecNode) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *VarSpecNode) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IDENT.Position() -} - -// VarSpec2Node represents the production -// -// VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . -type VarSpec2Node struct { - IdentifierList *IdentifierListNode - TypeNode Type - ASSIGN Token - ExpressionList *ExpressionListNode - lexicalScoper - - visible -} - -// Source implements Node. -func (n *VarSpec2Node) Source(full bool) string { return nodeSource(n, full) } - -// Position implements Node. -func (n *VarSpec2Node) Position() (r token.Position) { - if n == nil { - return r - } - - return n.IdentifierList.Position() -} - -func (p *parser) varSpec() Node { - var ( - identifierList *IdentifierListNode - typeNode Type - assignTok Token - expressionList *ExpressionListNode - ) - // ebnf.Sequence IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) ctx [IDENT] - { - ix := p.ix - // *ebnf.Name IdentifierList ctx [IDENT] - if identifierList = p.identifierList(); identifierList == nil { - p.back(ix) - return nil - } - // *ebnf.Group ( Type [ "=" ExpressionList ] | "=" ExpressionList ) ctx [] - // ebnf.Alternative Type [ "=" ExpressionList ] | "=" ExpressionList ctx [ARROW, ASSIGN, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - switch p.c() { - case ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT: // 0 - // ebnf.Sequence Type [ "=" ExpressionList ] ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - { - ix := p.ix - // *ebnf.Name Type ctx [ARROW, CHAN, FUNC, IDENT, INTERFACE, LBRACK, LPAREN, MAP, MUL, STRUCT] - if typeNode = p.type1(); typeNode == nil { - p.back(ix) - goto _0 - } - // *ebnf.Option [ "=" ExpressionList ] ctx [] - switch p.c() { - case ASSIGN: - // ebnf.Sequence "=" ExpressionList ctx [ASSIGN] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _2 - } - ix := p.ix - // *ebnf.Token "=" ctx [ASSIGN] - assignTok = p.expect(ASSIGN) - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _2 - } - } - } - goto _3 - _2: - assignTok = Token{} - expressionList = nil - _3: - } - break - _0: - assignTok = Token{} - expressionList = nil - typeNode = nil - p.back(ix) - return nil - case ASSIGN: // 1 - // ebnf.Sequence "=" ExpressionList ctx [ASSIGN] - { - switch p.peek(1) { - case ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR: - default: - goto _4 - } - ix := p.ix - // *ebnf.Token "=" ctx [ASSIGN] - assignTok = p.expect(ASSIGN) - // *ebnf.Name ExpressionList ctx [ADD, AND, ARROW, CHAN, CHAR, FLOAT, FUNC, IDENT, IMAG, INT, INTERFACE, LBRACK, LPAREN, MAP, MUL, NOT, STRING, STRUCT, SUB, XOR] - if expressionList = p.expressionList(false); expressionList == nil { - p.back(ix) - goto _4 - } - } - break - _4: - assignTok = Token{} - expressionList = nil - p.back(ix) - return nil - default: - p.back(ix) - return nil - } - } - sc := p.sc - if identifierList.Len() == 1 { - r := &VarSpecNode{ - lexicalScoper: newLexicalScoper(sc), - IDENT: identifierList.IDENT, - TypeNode: typeNode, - ASSIGN: assignTok, - ExpressionList: expressionList, - } - visible := int32(p.ix) - p.declare(sc, r.IDENT, r, visible, false) - return r - } - - r := &VarSpec2Node{ - lexicalScoper: newLexicalScoper(sc), - IdentifierList: identifierList, - TypeNode: typeNode, - ASSIGN: assignTok, - ExpressionList: expressionList, - } - visible := int32(p.ix) - for l := r.IdentifierList; l != nil; l = l.List { - p.declare(sc, l.IDENT, r, visible, false) - } - return r -} - -const ( - balanceZero = iota - balanceTuple - balanceEqual - balanceExtraRhs - balanceExtraLhs -) - -func checkBalance(lhs, rhs int) int { - switch { - case lhs == rhs: - return balanceEqual - case lhs > 1 && rhs == 1: - return balanceTuple - case lhs > rhs: - return balanceExtraLhs - case lhs < rhs: - return balanceExtraRhs - default: - panic(todo("", lhs, rhs)) - } -} diff --git a/vendor/modernc.org/gc/v3/scanner.go b/vendor/modernc.org/gc/v3/scanner.go deleted file mode 100644 index a3815a8f8..000000000 --- a/vendor/modernc.org/gc/v3/scanner.go +++ /dev/null @@ -1,1446 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // import "modernc.org/gc/v3" - -import ( - "bytes" - "fmt" - "go/token" - "path/filepath" - "strings" - "unicode" - "unicode/utf8" - - "modernc.org/mathutil" - mtoken "modernc.org/token" -) - -var ( - _ Node = (*Token)(nil) - _ Node = (*nonode)(nil) - - keywords = map[string]token.Token{ - "break": BREAK, - "case": CASE, - "chan": CHAN, - "const": CONST, - "continue": CONTINUE, - "default": DEFAULT, - "defer": DEFER, - "else": ELSE, - "fallthrough": FALLTHROUGH, - "for": FOR, - "func": FUNC, - "go": GO, - "goto": GOTO, - "if": IF, - "import": IMPORT, - "interface": INTERFACE, - "map": MAP, - "package": PACKAGE, - "range": RANGE, - "return": RETURN, - "select": SELECT, - "struct": STRUCT, - "switch": SWITCH, - "type": TYPE, - "var": VAR, - } - - lineCommentTag = []byte("line ") - znode = &nonode{} -) - -type nonode struct{} - -func (*nonode) Position() (r token.Position) { return r } -func (*nonode) Source(full bool) string { return "" } - -// Token represents a lexeme, its position and its semantic value. -type Token struct { // 16 bytes on 64 bit arch - source *source - - ch int32 - index int32 -} - -// Ch returns which token t represents -func (t Token) Ch() token.Token { return token.Token(t.ch) } - -// Source implements Node. -func (t Token) Source(full bool) string { - // trc("%10s %v: #%v sep %v, src %v, buf %v", tokSource(t.Ch()), t.Position(), t.index, t.source.toks[t.index].sep, t.source.toks[t.index].src, len(t.source.buf)) - sep := t.Sep() - if !full && sep != "" { - sep = " " - } - src := t.Src() - if !full && strings.ContainsRune(src, '\n') { - src = " " - } - // trc("%q %q -> %q %q", t.Sep(), t.Src(), sep, src) - return sep + src -} - -// Positions implements Node. -func (t Token) Position() (r token.Position) { - if t.source == nil { - return r - } - - s := t.source - off := mathutil.MinInt32(int32(len(s.buf)), s.toks[t.index].src) - return token.Position(s.file.PositionFor(mtoken.Pos(s.base+off), true)) -} - -// Prev returns the token preceding t or a zero value if no such token exists. -func (t Token) Prev() (r Token) { - if index := t.index - 1; index >= 0 { - s := t.source - return Token{source: s, ch: s.toks[index].ch, index: index} - } - - return r -} - -// Next returns the token following t or a zero value if no such token exists. -func (t Token) Next() (r Token) { - if index := t.index + 1; index < int32(len(t.source.toks)) { - s := t.source - return Token{source: s, ch: s.toks[index].ch, index: index} - } - - return r -} - -// Sep returns any separators, combined, preceding t. -func (t Token) Sep() string { - s := t.source - if p, ok := s.sepPatches[t.index]; ok { - return p - } - - return string(s.buf[s.toks[t.index].sep:s.toks[t.index].src]) -} - -// SetSep sets t's separator. -func (t Token) SetSep(s string) { - src := t.source - if src.sepPatches == nil { - src.sepPatches = map[int32]string{} - } - src.sepPatches[t.index] = s -} - -// Src returns t's source form. -func (t Token) Src() string { - s := t.source - if p, ok := s.srcPatches[t.index]; ok { - return p - } - - if t.ch != int32(EOF) { - next := t.source.off - if t.index < int32(len(s.toks))-1 { - next = s.toks[t.index+1].sep - } - return string(s.buf[s.toks[t.index].src:next]) - } - - return "" -} - -// SetSrc sets t's source form. -func (t Token) SetSrc(s string) { - src := t.source - if src.srcPatches == nil { - src.srcPatches = map[int32]string{} - } - src.srcPatches[t.index] = s -} - -// IsValid reports t is a valid token. Zero value reports false. -func (t Token) IsValid() bool { return t.source != nil } - -type tok struct { // 12 bytes - ch int32 - sep int32 - src int32 -} - -func (t *tok) token() token.Token { return token.Token(t.ch) } - -func (t *tok) position(s *source) (r token.Position) { - off := mathutil.MinInt32(int32(len(s.buf)), t.src) - return token.Position(s.file.PositionFor(mtoken.Pos(s.base+off), true)) -} - -// source represents a single Go source file, editor text buffer etc. -type source struct { - buf []byte - file *mtoken.File - name string - sepPatches map[int32]string - srcPatches map[int32]string - toks []tok - - base int32 - off int32 -} - -// 'buf' becomes owned by the result and must not be modified afterwards. -func newSource(name string, buf []byte) *source { - file := mtoken.NewFile(name, len(buf)) - return &source{ - buf: buf, - file: file, - name: name, - base: int32(file.Base()), - } -} - -type ErrWithPosition struct { - pos token.Position - err error -} - -func (e ErrWithPosition) String() string { - switch { - case e.pos.IsValid(): - return fmt.Sprintf("%v: %v", e.pos, e.err) - default: - return fmt.Sprintf("%v", e.err) - } -} - -type errList []ErrWithPosition - -func (e errList) Err() (r error) { - if len(e) == 0 { - return nil - } - - return e -} - -func (e errList) Error() string { - w := 0 - prev := ErrWithPosition{pos: token.Position{Offset: -1}} - for _, v := range e { - if v.pos.Line == 0 || v.pos.Offset != prev.pos.Offset || v.err.Error() != prev.err.Error() { - e[w] = v - w++ - prev = v - } - } - - var a []string - for _, v := range e { - a = append(a, fmt.Sprint(v)) - } - return strings.Join(a, "\n") -} - -func (e *errList) err(pos token.Position, msg string, args ...interface{}) { - if trcErrors { - trc("FAIL "+msg, args...) - } - switch { - case len(args) == 0: - *e = append(*e, ErrWithPosition{pos, fmt.Errorf("%s", msg)}) - default: - *e = append(*e, ErrWithPosition{pos, fmt.Errorf(msg, args...)}) - } -} - -type scanner struct { - *source - dir string - errs errList - tok tok - - last int32 - - errBudget int - - c byte // Lookahead byte. - - eof bool - isClosed bool -} - -func newScanner(name string, buf []byte) *scanner { - dir, _ := filepath.Split(name) - r := &scanner{source: newSource(name, buf), errBudget: 10, dir: dir} - switch { - case len(buf) == 0: - r.eof = true - default: - r.c = buf[0] - if r.c == '\n' { - r.file.AddLine(int(r.base + r.off)) - } - } - return r -} - -func isDigit(c byte) bool { return c >= '0' && c <= '9' } -func isHexDigit(c byte) bool { return isDigit(c) || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' } -func isIDNext(c byte) bool { return isIDFirst(c) || isDigit(c) } -func isOctalDigit(c byte) bool { return c >= '0' && c <= '7' } - -func isIDFirst(c byte) bool { - return c >= 'a' && c <= 'z' || - c >= 'A' && c <= 'Z' || - c == '_' -} - -func (s *scanner) position() token.Position { - return token.Position(s.source.file.PositionFor(mtoken.Pos(s.base+s.off), true)) -} - -func (s *scanner) pos(off int32) token.Position { - return token.Position(s.file.PositionFor(mtoken.Pos(s.base+off), true)) -} - -func (s *scanner) token() Token { - return Token{source: s.source, ch: s.tok.ch, index: int32(len(s.toks) - 1)} -} - -func (s *scanner) err(off int32, msg string, args ...interface{}) { - if s.errBudget <= 0 { - s.close() - return - } - - s.errBudget-- - if n := int32(len(s.buf)); off >= n { - off = n - } - s.errs.err(s.pos(off), msg, args...) -} - -func (s *scanner) close() { - if s.isClosed { - return - } - - s.tok.ch = int32(ILLEGAL) - s.eof = true - s.isClosed = true -} - -func (s *scanner) next() { - if s.eof { - return - } - - s.off++ - if int(s.off) == len(s.buf) { - s.c = 0 - s.eof = true - return - } - - s.c = s.buf[s.off] - if s.c == '\n' { - s.file.AddLine(int(s.base + s.off)) - } -} - -func (s *scanner) nextN(n int) { - if int(s.off) == len(s.buf)-n { - s.c = 0 - s.eof = true - return - } - - s.off += int32(n) - s.c = s.buf[s.off] - if s.c == '\n' { - s.file.AddLine(int(s.base + s.off)) - } -} - -func (s *scanner) scan() (r bool) { - if s.isClosed { - return false - } - - s.last = s.tok.ch - s.tok.sep = s.off - s.tok.ch = -1 - for { - if r = s.scan0(); !r || s.tok.ch >= 0 { - s.toks = append(s.toks, s.tok) - // trc("", dump(s.token())) - return r - } - } -} - -func (s *scanner) scan0() (r bool) { - s.tok.src = mathutil.MinInt32(s.off, int32(len(s.buf))) - switch s.c { - case ' ', '\t', '\r', '\n': - // White space, formed from spaces (U+0020), horizontal tabs (U+0009), carriage - // returns (U+000D), and newlines (U+000A), is ignored except as it separates - // tokens that would otherwise combine into a single token. - if s.c == '\n' && s.injectSemi() { - return true - } - - s.next() - return true - case '/': - off := s.off - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(QUO_ASSIGN) - case '/': - // Line comments start with the character sequence // and stop at the end of - // the line. - s.next() - s.lineComment(off) - return true - case '*': - // General comments start with the character sequence /* and stop with the - // first subsequent character sequence */. - s.next() - s.generalComment(off) - return true - default: - s.tok.ch = int32(QUO) - } - case '(': - s.tok.ch = int32(LPAREN) - s.next() - case ')': - s.tok.ch = int32(RPAREN) - s.next() - case '[': - s.tok.ch = int32(LBRACK) - s.next() - case ']': - s.tok.ch = int32(RBRACK) - s.next() - case '{': - s.tok.ch = int32(LBRACE) - s.next() - case '}': - s.tok.ch = int32(RBRACE) - s.next() - case ',': - s.tok.ch = int32(COMMA) - s.next() - case ';': - s.tok.ch = int32(SEMICOLON) - s.next() - case '~': - s.tok.ch = int32(TILDE) - s.next() - case '"': - off := s.off - s.next() - s.stringLiteral(off) - case '\'': - off := s.off - s.next() - s.runeLiteral(off) - case '`': - s.next() - for { - switch { - case s.c == '`': - s.next() - s.tok.ch = int32(STRING) - return true - case s.eof: - s.err(s.off, "raw string literal not terminated") - s.tok.ch = int32(STRING) - return true - case s.c == 0: - panic(todo("%v: %#U", s.position(), s.c)) - default: - s.next() - } - } - case '.': - s.next() - off := s.off - if isDigit(s.c) { - s.dot(false, true) - return true - } - - if s.c != '.' { - s.tok.ch = int32(PERIOD) - return true - } - - s.next() - if s.c != '.' { - s.off = off - s.c = '.' - s.tok.ch = int32(PERIOD) - return true - } - - s.next() - s.tok.ch = int32(ELLIPSIS) - return true - case '%': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(REM_ASSIGN) - default: - s.tok.ch = int32(REM) - } - case '*': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(MUL_ASSIGN) - default: - s.tok.ch = int32(MUL) - } - case '^': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(XOR_ASSIGN) - default: - s.tok.ch = int32(XOR) - } - case '+': - s.next() - switch s.c { - case '+': - s.next() - s.tok.ch = int32(INC) - case '=': - s.next() - s.tok.ch = int32(ADD_ASSIGN) - default: - s.tok.ch = int32(ADD) - } - case '-': - s.next() - switch s.c { - case '-': - s.next() - s.tok.ch = int32(DEC) - case '=': - s.next() - s.tok.ch = int32(SUB_ASSIGN) - default: - s.tok.ch = int32(SUB) - } - case ':': - s.next() - switch { - case s.c == '=': - s.next() - s.tok.ch = int32(DEFINE) - default: - s.tok.ch = int32(COLON) - } - case '=': - s.next() - switch { - case s.c == '=': - s.next() - s.tok.ch = int32(EQL) - default: - s.tok.ch = int32(ASSIGN) - } - case '!': - s.next() - switch { - case s.c == '=': - s.next() - s.tok.ch = int32(NEQ) - default: - s.tok.ch = int32(NOT) - } - case '>': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(GEQ) - case '>': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(SHR_ASSIGN) - default: - s.tok.ch = int32(SHR) - } - default: - s.tok.ch = int32(GTR) - } - case '<': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(LEQ) - case '<': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(SHL_ASSIGN) - default: - s.tok.ch = int32(SHL) - } - case '-': - s.next() - s.tok.ch = int32(ARROW) - default: - s.tok.ch = int32(LSS) - } - case '|': - s.next() - switch s.c { - case '|': - s.next() - s.tok.ch = int32(LOR) - case '=': - s.next() - s.tok.ch = int32(OR_ASSIGN) - default: - s.tok.ch = int32(OR) - } - case '&': - s.next() - switch s.c { - case '&': - s.next() - s.tok.ch = int32(LAND) - case '^': - s.next() - switch s.c { - case '=': - s.next() - s.tok.ch = int32(AND_NOT_ASSIGN) - default: - s.tok.ch = int32(AND_NOT) - } - case '=': - s.next() - s.tok.ch = int32(AND_ASSIGN) - default: - s.tok.ch = int32(AND) - } - default: - switch { - case isIDFirst(s.c): - s.next() - s.identifierOrKeyword() - case isDigit(s.c): - s.numericLiteral() - case s.c >= 0x80: - off := s.off - switch r := s.rune(); { - case unicode.IsLetter(r): - s.identifierOrKeyword() - case r == 0xfeff: - if off == 0 { // Ignore BOM, but only at buffer start. - return true - } - - s.err(off, "illegal byte order mark") - s.tok.ch = int32(ILLEGAL) - default: - s.err(s.off, "illegal character %#U", r) - s.tok.ch = int32(ILLEGAL) - } - case s.eof: - if s.injectSemi() { - return true - } - - s.close() - s.tok.ch = int32(EOF) - s.tok.sep = mathutil.MinInt32(s.tok.sep, s.tok.src) - return false - // case s.c == 0: - // panic(todo("%v: %#U", s.position(), s.c)) - default: - s.err(s.off, "illegal character %#U", s.c) - s.next() - s.tok.ch = int32(ILLEGAL) - } - } - return true -} - -func (s *scanner) runeLiteral(off int32) { - // Leading ' consumed. - ok := 0 - s.tok.ch = int32(CHAR) - expOff := int32(-1) - if s.eof { - s.err(off, "rune literal not terminated") - return - } - - for { - switch s.c { - case '\\': - ok++ - s.next() - switch s.c { - case '\'', '\\', 'a', 'b', 'f', 'n', 'r', 't', 'v': - s.next() - case 'x', 'X': - s.next() - for i := 0; i < 2; i++ { - if s.c == '\'' { - if i != 2 { - s.err(s.off, "illegal character %#U in escape sequence", s.c) - } - s.next() - return - } - - if !isHexDigit(s.c) { - s.err(s.off, "illegal character %#U in escape sequence", s.c) - break - } - s.next() - } - case 'u': - s.u(4) - case 'U': - s.u(8) - default: - switch { - case s.eof: - s.err(s.base+s.off, "escape sequence not terminated") - return - case isOctalDigit(s.c): - for i := 0; i < 3; i++ { - s.next() - if s.c == '\'' { - if i != 2 { - s.err(s.off, "illegal character %#U in escape sequence", s.c) - } - s.next() - return - } - - if !isOctalDigit(s.c) { - s.err(s.off, "illegal character %#U in escape sequence", s.c) - break - } - } - default: - s.err(s.off, "unknown escape sequence") - } - } - case '\'': - s.next() - if ok != 1 { - s.err(off, "illegal rune literal") - } - return - case '\t': - s.next() - ok++ - default: - switch { - case s.eof: - switch { - case ok != 0: - s.err(expOff, "rune literal not terminated") - default: - s.err(s.base+s.off, "rune literal not terminated") - } - return - case s.c == 0: - panic(todo("%v: %#U", s.position(), s.c)) - case s.c < ' ': - ok++ - s.err(s.off, "non-printable character: %#U", s.c) - s.next() - case s.c >= 0x80: - ok++ - off := s.off - if c := s.rune(); c == 0xfeff { - s.err(off, "illegal byte order mark") - } - default: - ok++ - s.next() - } - } - if ok != 0 && expOff < 0 { - expOff = s.off - if s.eof { - expOff++ - } - } - } -} - -func (s *scanner) stringLiteral(off int32) { - // Leadind " consumed. - s.tok.ch = int32(STRING) - for { - switch { - case s.c == '"': - s.next() - return - case s.c == '\\': - s.next() - switch s.c { - case '"', '\\', 'a', 'b', 'f', 'n', 'r', 't', 'v': - s.next() - continue - case 'x', 'X': - s.next() - if !isHexDigit(s.c) { - panic(todo("%v: %#U", s.position(), s.c)) - } - - s.next() - if !isHexDigit(s.c) { - panic(todo("%v: %#U", s.position(), s.c)) - } - - s.next() - continue - case 'u': - s.u(4) - continue - case 'U': - s.u(8) - continue - default: - switch { - case isOctalDigit(s.c): - s.next() - if isOctalDigit(s.c) { - s.next() - } - if isOctalDigit(s.c) { - s.next() - } - continue - default: - s.err(off-1, "unknown escape sequence") - } - } - case s.c == '\n': - fallthrough - case s.eof: - s.err(off, "string literal not terminated") - return - case s.c == 0: - s.err(s.off, "illegal character NUL") - } - - switch { - case s.c >= 0x80: - off := s.off - if s.rune() == 0xfeff { - s.err(off, "illegal byte order mark") - } - continue - } - - s.next() - } -} - -func (s *scanner) u(n int) (r rune) { - // Leading u/U not consumed. - s.next() - off := s.off - for i := 0; i < n; i++ { - switch { - case isHexDigit(s.c): - var n rune - switch { - case s.c >= '0' && s.c <= '9': - n = rune(s.c) - '0' - case s.c >= 'a' && s.c <= 'f': - n = rune(s.c) - 'a' + 10 - case s.c >= 'A' && s.c <= 'F': - n = rune(s.c) - 'A' + 10 - } - r = 16*r + n - default: - switch { - case s.eof: - s.err(s.base+s.off, "escape sequence not terminated") - default: - s.err(s.off, "illegal character %#U in escape sequence", s.c) - } - return r - } - - s.next() - } - if r < 0 || r > unicode.MaxRune || r >= 0xd800 && r <= 0xdfff { - s.err(off-1, "escape sequence is invalid Unicode code point") - } - return r -} - -func (s *scanner) identifierOrKeyword() { -out: - for { - switch { - case isIDNext(s.c): - s.next() - case s.c >= 0x80: - off := s.off - c := s.c - switch r := s.rune(); { - case unicode.IsLetter(r) || unicode.IsDigit(r): - // already consumed - default: - s.off = off - s.c = c - break out - } - case s.eof: - break out - case s.c == 0: - s.err(s.off, "illegal character NUL") - break out - default: - break out - } - } - if s.tok.ch = int32(keywords[string(s.buf[s.tok.src:s.off])]); s.tok.ch == 0 { - s.tok.ch = int32(IDENT) - } -} - -func (s *scanner) numericLiteral() { - // Leading decimal digit not consumed. - var hasHexMantissa, needFrac bool -more: - switch s.c { - case '0': - s.next() - switch s.c { - case '.': - // nop - case 'b', 'B': - s.next() - s.binaryLiteral() - return - case 'e', 'E': - s.exponent() - s.tok.ch = int32(FLOAT) - return - case 'p', 'P': - s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c) - s.exponent() - s.tok.ch = int32(FLOAT) - return - case 'o', 'O': - s.next() - s.octalLiteral() - return - case 'x', 'X': - hasHexMantissa = true - needFrac = true - s.tok.ch = int32(INT) - s.next() - if s.c == '.' { - s.next() - s.dot(hasHexMantissa, needFrac) - return - } - - if s.hexadecimals() == 0 { - s.err(s.base+s.off, "hexadecimal literal has no digits") - return - } - - needFrac = false - case 'i': - s.next() - s.tok.ch = int32(IMAG) - return - default: - invalidOff := int32(-1) - var invalidDigit byte - for { - if s.c == '_' { - for n := 0; s.c == '_'; n++ { - if n == 1 { - s.err(s.off, "'_' must separate successive digits") - } - s.next() - } - if !isDigit(s.c) { - s.err(s.off-1, "'_' must separate successive digits") - } - } - if isOctalDigit(s.c) { - s.next() - continue - } - - if isDigit(s.c) { - if invalidOff < 0 { - invalidOff = s.off - invalidDigit = s.c - } - s.next() - continue - } - - break - } - switch s.c { - case '.', 'e', 'E', 'i': - break more - } - if isDigit(s.c) { - break more - } - if invalidOff > 0 { - s.err(invalidOff, "invalid digit '%c' in octal literal", invalidDigit) - } - s.tok.ch = int32(INT) - return - } - default: - s.decimals() - } - switch s.c { - case '.': - s.next() - s.dot(hasHexMantissa, needFrac) - case 'p', 'P': - if !hasHexMantissa { - s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c) - } - fallthrough - case 'e', 'E': - s.exponent() - if s.c == 'i' { - s.next() - s.tok.ch = int32(IMAG) - return - } - - s.tok.ch = int32(FLOAT) - case 'i': - s.next() - s.tok.ch = int32(IMAG) - default: - s.tok.ch = int32(INT) - } -} - -func (s *scanner) octalLiteral() { - // Leading 0o consumed. - ok := false - invalidOff := int32(-1) - var invalidDigit byte - s.tok.ch = int32(INT) - for { - for n := 0; s.c == '_'; n++ { - if n == 1 { - s.err(s.off, "'_' must separate successive digits") - } - s.next() - } - switch s.c { - case '0', '1', '2', '3', '4', '5', '6', '7': - s.next() - ok = true - case '8', '9': - if invalidOff < 0 { - invalidOff = s.off - invalidDigit = s.c - } - s.next() - case '.': - s.tok.ch = int32(FLOAT) - s.err(s.off, "invalid radix point in octal literal") - s.next() - case 'e', 'E': - s.tok.ch = int32(FLOAT) - s.err(s.off, "'%c' exponent requires decimal mantissa", s.c) - s.exponent() - case 'p', 'P': - s.tok.ch = int32(FLOAT) - s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c) - s.exponent() - default: - switch { - case !ok: - s.err(s.base+s.off, "octal literal has no digits") - case invalidOff > 0: - s.err(invalidOff, "invalid digit '%c' in octal literal", invalidDigit) - } - if s.c == 'i' { - s.next() - s.tok.ch = int32(IMAG) - } - return - } - } -} - -func (s *scanner) binaryLiteral() { - // Leading 0b consumed. - ok := false - invalidOff := int32(-1) - var invalidDigit byte - s.tok.ch = int32(INT) - for { - for n := 0; s.c == '_'; n++ { - if n == 1 { - s.err(s.off, "'_' must separate successive digits") - } - s.next() - } - switch s.c { - case '0', '1': - s.next() - ok = true - case '.': - s.tok.ch = int32(FLOAT) - s.err(s.off, "invalid radix point in binary literal") - s.next() - case 'e', 'E': - s.tok.ch = int32(FLOAT) - s.err(s.off, "'%c' exponent requires decimal mantissa", s.c) - s.exponent() - case 'p', 'P': - s.tok.ch = int32(FLOAT) - s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c) - s.exponent() - default: - if isDigit(s.c) { - if invalidOff < 0 { - invalidOff = s.off - invalidDigit = s.c - } - s.next() - continue - } - - switch { - case !ok: - s.err(s.base+s.off, "binary literal has no digits") - case invalidOff > 0: - s.err(invalidOff, "invalid digit '%c' in binary literal", invalidDigit) - } - if s.c == 'i' { - s.next() - s.tok.ch = int32(IMAG) - } - return - } - } -} - -func (s *scanner) generalComment(off int32) (injectSemi bool) { - // Leading /* consumed - off0 := s.off - 2 - var nl bool - for { - switch { - case s.c == '*': - s.next() - switch s.c { - case '/': - s.lineInfo(off0, s.off+1) - s.next() - if nl { - return s.injectSemi() - } - - return false - } - case s.c == '\n': - nl = true - s.next() - case s.eof: - s.tok.ch = 0 - s.err(off, "comment not terminated") - return true - case s.c == 0: - panic(todo("%v: %#U", s.position(), s.c)) - default: - s.next() - } - } -} - -func (s *scanner) lineComment(off int32) (injectSemi bool) { - // Leading // consumed - off0 := s.off - 2 - for { - switch { - case s.c == '\n': - s.lineInfo(off0, s.off+1) - if s.injectSemi() { - return true - } - - s.next() - return false - case s.c >= 0x80: - if c := s.rune(); c == 0xfeff { - s.err(off+2, "illegal byte order mark") - } - case s.eof: - s.off++ - if s.injectSemi() { - return true - } - - return false - case s.c == 0: - return false - default: - s.next() - } - } -} - -func (s *scanner) lineInfo(off, next int32) { - if off != 0 && s.buf[off+1] != '*' && s.buf[off-1] != '\n' && s.buf[off-1] != '\r' { - return - } - - str := s.buf[off:next] - if !bytes.HasPrefix(str[len("//"):], lineCommentTag) { - return - } - - switch { - case str[1] == '*': - str = str[:len(str)-len("*/")] - default: - str = str[:len(str)-len("\n")] - } - str = str[len("//"):] - - str, ln, ok := s.lineInfoNum(str[len("line "):]) - col := 0 - if ok == liBadNum || ok == liNoNum { - return - } - - hasCol := false - var n int - if str, n, ok = s.lineInfoNum(str); ok == liBadNum { - return - } - - if ok != liNoNum { - col = ln - ln = n - hasCol = true - } - - fn := strings.TrimSpace(string(str)) - switch { - case fn == "" && hasCol: - fn = s.pos(off).Filename - case fn != "": - fn = filepath.Clean(fn) - if !filepath.IsAbs(fn) { - fn = filepath.Join(s.dir, fn) - } - } - // trc("set %v %q %v %v", next, fn, ln, col) - s.file.AddLineColumnInfo(int(next), fn, ln, col) -} - -const ( - liNoNum = iota - liBadNum - liOK -) - -func (s *scanner) lineInfoNum(str []byte) (_ []byte, n, r int) { - // trc("==== %q", str) - x := len(str) - 1 - if x < 0 || !isDigit(str[x]) { - return str, 0, liNoNum - } - - mul := 1 - for x > 0 && isDigit(str[x]) { - n += mul * (int(str[x]) - '0') - mul *= 10 - x-- - if n < 0 { - return str, 0, liBadNum - } - } - if x < 0 || str[x] != ':' { - return str, 0, liBadNum - } - - // trc("---- %q %v %v", str[:x], n, liOK) - return str[:x], n, liOK -} - -func (s *scanner) rune() rune { - switch r, sz := utf8.DecodeRune(s.buf[s.off:]); { - case r == utf8.RuneError && sz == 0: - panic(todo("%v: %#U", s.position(), s.c)) - case r == utf8.RuneError && sz == 1: - s.err(s.off, "illegal UTF-8 encoding") - s.next() - return r - default: - s.nextN(sz) - return r - } -} - -func (s *scanner) dot(hasHexMantissa, needFrac bool) { - // '.' already consumed - switch { - case hasHexMantissa: - if s.hexadecimals() == 0 && needFrac { - s.err(s.off, "hexadecimal literal has no digits") - } - switch s.c { - case 'p', 'P': - // ok - default: - s.err(s.off, "hexadecimal mantissa requires a 'p' exponent") - } - default: - if s.decimals() == 0 && needFrac { - panic(todo("%v: %#U", s.position(), s.c)) - } - } - switch s.c { - case 'p', 'P': - if !hasHexMantissa { - s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c) - } - fallthrough - case 'e', 'E': - s.exponent() - if s.c == 'i' { - s.next() - s.tok.ch = int32(IMAG) - return - } - - s.tok.ch = int32(FLOAT) - case 'i': - s.next() - s.tok.ch = int32(IMAG) - default: - s.tok.ch = int32(FLOAT) - } -} - -func (s *scanner) exponent() { - // Leanding e or E not consumed. - s.next() - switch s.c { - case '+', '-': - s.next() - } - if !isDigit(s.c) { - s.err(s.base+s.off, "exponent has no digits") - return - } - - s.decimals() -} - -func (s *scanner) decimals() (r int) { - first := true - for { - switch { - case isDigit(s.c): - first = false - s.next() - r++ - case s.c == '_': - for n := 0; s.c == '_'; n++ { - if first || n == 1 { - s.err(s.off, "'_' must separate successive digits") - } - s.next() - } - if !isDigit(s.c) { - s.err(s.off-1, "'_' must separate successive digits") - } - default: - return r - } - } -} - -func (s *scanner) hexadecimals() (r int) { - for { - switch { - case isHexDigit(s.c): - s.next() - r++ - case s.c == '_': - for n := 0; s.c == '_'; n++ { - if n == 1 { - s.err(s.off, "'_' must separate successive digits") - } - s.next() - } - if !isHexDigit(s.c) { - s.err(s.off-1, "'_' must separate successive digits") - } - default: - return r - } - } -} - -// When the input is broken into tokens, a semicolon is automatically inserted -// into the token stream immediately after a line's final token if that token -// is -// -// - an identifier -// - an integer, floating-point, imaginary, rune, or string literal -// - one of the keywords break, continue, fallthrough, or return -// - one of the operators and punctuation ++, --, ), ], or } -func (s *scanner) injectSemi() bool { - switch token.Token(s.last) { - case - IDENT, INT, FLOAT, IMAG, CHAR, STRING, - BREAK, CONTINUE, FALLTHROUGH, RETURN, - INC, DEC, RPAREN, RBRACK, RBRACE: - - s.tok.ch = int32(SEMICOLON) - s.last = 0 - if s.c == '\n' { - s.next() - } - return true - } - - s.last = 0 - return false -} diff --git a/vendor/modernc.org/gc/v3/stringer.go b/vendor/modernc.org/gc/v3/stringer.go deleted file mode 100644 index 2a435f37b..000000000 --- a/vendor/modernc.org/gc/v3/stringer.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by "stringer -output stringer.go -linecomment -type=Kind,ScopeKind,ChanDir,TypeCheck"; DO NOT EDIT. - -package gc - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[InvalidKind-0] - _ = x[Array-1] - _ = x[Bool-2] - _ = x[Chan-3] - _ = x[Complex128-4] - _ = x[Complex64-5] - _ = x[Float32-6] - _ = x[Float64-7] - _ = x[Function-8] - _ = x[Int-9] - _ = x[Int16-10] - _ = x[Int32-11] - _ = x[Int64-12] - _ = x[Int8-13] - _ = x[Interface-14] - _ = x[Map-15] - _ = x[Pointer-16] - _ = x[Slice-17] - _ = x[String-18] - _ = x[Struct-19] - _ = x[Tuple-20] - _ = x[Uint-21] - _ = x[Uint16-22] - _ = x[Uint32-23] - _ = x[Uint64-24] - _ = x[Uint8-25] - _ = x[Uintptr-26] - _ = x[UnsafePointer-27] - _ = x[UntypedBool-28] - _ = x[UntypedComplex-29] - _ = x[UntypedFloat-30] - _ = x[UntypedInt-31] - _ = x[UntypedNil-32] - _ = x[UntypedRune-33] - _ = x[UntypedString-34] -} - -const _Kind_name = "arrayboolchancomplex128complex64float32float64functionintint16int32int64int8interfacemappointerslicestringstructtupleuintuint16uint32uint64uint8uintptrunsafe.Pointeruntyped booluntyped complexuntyped floatuntyped intuntyped niluntyped runeuntyped string" - -var _Kind_index = [...]uint16{0, 14, 19, 23, 27, 37, 46, 53, 60, 68, 71, 76, 81, 86, 90, 99, 102, 109, 114, 120, 126, 131, 135, 141, 147, 153, 158, 165, 179, 191, 206, 219, 230, 241, 253, 267} - -func (i Kind) String() string { - if i >= Kind(len(_Kind_index)-1) { - return "Kind(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Kind_name[_Kind_index[i]:_Kind_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[scZero-0] - _ = x[UniverseScope-1] - _ = x[PackageScope-2] - _ = x[FileScope-3] - _ = x[OtherScope-4] -} - -const _ScopeKind_name = "scZeroUniverseScopePackageScopeFileScopeOtherScope" - -var _ScopeKind_index = [...]uint8{0, 6, 19, 31, 40, 50} - -func (i ScopeKind) String() string { - if i < 0 || i >= ScopeKind(len(_ScopeKind_index)-1) { - return "ScopeKind(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _ScopeKind_name[_ScopeKind_index[i]:_ScopeKind_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[SendRecv-0] - _ = x[SendOnly-1] - _ = x[RecvOnly-2] -} - -const _ChanDir_name = "SendRecvSendOnlyRecvOnly" - -var _ChanDir_index = [...]uint8{0, 8, 16, 24} - -func (i ChanDir) String() string { - if i < 0 || i >= ChanDir(len(_ChanDir_index)-1) { - return "ChanDir(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _ChanDir_name[_ChanDir_index[i]:_ChanDir_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[TypeCheckNone-0] - _ = x[TypeCheckAll-1] -} - -const _TypeCheck_name = "TypeCheckNoneTypeCheckAll" - -var _TypeCheck_index = [...]uint8{0, 13, 25} - -func (i TypeCheck) String() string { - if i < 0 || i >= TypeCheck(len(_TypeCheck_index)-1) { - return "TypeCheck(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _TypeCheck_name[_TypeCheck_index[i]:_TypeCheck_index[i+1]] -} diff --git a/vendor/modernc.org/gc/v3/syslist.go b/vendor/modernc.org/gc/v3/syslist.go deleted file mode 100644 index 0f2cded9e..000000000 --- a/vendor/modernc.org/gc/v3/syslist.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the GO-LICENSE file. - -// Modifications -// -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// package build // /usr/local/go/src/go/build/syslist.go - -package gc // import "modernc.org/gc/v3" - -// Go 1.19.3 - -// Note that this file is read by internal/goarch/gengoarch.go and by -// internal/goos/gengoos.go. If you change this file, look at those -// files as well. - -// knownOS is the list of past, present, and future known GOOS values. -// Do not remove from this list, as it is used for filename matching. -// If you add an entry to this list, look at unixOS, below. -var knownOS = map[string]bool{ - "aix": true, - "android": true, - "darwin": true, - "dragonfly": true, - "freebsd": true, - "hurd": true, - "illumos": true, - "ios": true, - "js": true, - "linux": true, - "nacl": true, - "netbsd": true, - "openbsd": true, - "plan9": true, - "solaris": true, - "windows": true, - "zos": true, -} - -// unixOS is the set of GOOS values matched by the "unix" build tag. -// This is not used for filename matching. -// This list also appears in cmd/dist/build.go and -// cmd/go/internal/imports/build.go. -var unixOS = map[string]bool{ - "aix": true, - "android": true, - "darwin": true, - "dragonfly": true, - "freebsd": true, - "hurd": true, - "illumos": true, - "ios": true, - "linux": true, - "netbsd": true, - "openbsd": true, - "solaris": true, -} - -// knownArch is the list of past, present, and future known GOARCH values. -// Do not remove from this list, as it is used for filename matching. -var knownArch = map[string]bool{ - "386": true, - "amd64": true, - "amd64p32": true, - "arm": true, - "armbe": true, - "arm64": true, - "arm64be": true, - "loong64": true, - "mips": true, - "mipsle": true, - "mips64": true, - "mips64le": true, - "mips64p32": true, - "mips64p32le": true, - "ppc": true, - "ppc64": true, - "ppc64le": true, - "riscv": true, - "riscv64": true, - "s390": true, - "s390x": true, - "sparc": true, - "sparc64": true, - "wasm": true, -} diff --git a/vendor/modernc.org/gc/v3/type.go b/vendor/modernc.org/gc/v3/type.go deleted file mode 100644 index 5382c2cef..000000000 --- a/vendor/modernc.org/gc/v3/type.go +++ /dev/null @@ -1,813 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // modernc.org/gc/v3 - -import ( - "fmt" - "go/token" - "strings" -) - -var ( - Invalid = &InvalidType{} -) - -var ( - _ Type = (*ArrayTypeNode)(nil) - _ Type = (*ChannelTypeNode)(nil) - _ Type = (*FunctionTypeNode)(nil) - _ Type = (*InterfaceTypeNode)(nil) - _ Type = (*InvalidType)(nil) - _ Type = (*MapTypeNode)(nil) - _ Type = (*ParenthesizedTypeNode)(nil) - _ Type = (*PointerTypeNode)(nil) - _ Type = (*PredeclaredType)(nil) - _ Type = (*SliceTypeNode)(nil) - _ Type = (*StructTypeNode)(nil) - _ Type = (*TupleType)(nil) - _ Type = (*TypeDefNode)(nil) - _ Type = (*TypeNameNode)(nil) - _ Type = (*TypeNode)(nil) - - invalidRecursiveType = &InvalidType{} -) - -// A Kind represents the specific kind of type that a Type represents. The zero -// Kind is not a valid kind. -type Kind byte - -// Values of type Kind -const ( - InvalidKind Kind = iota // - - Array // array - Bool // bool - Chan // chan - Complex128 // complex128 - Complex64 // complex64 - Float32 // float32 - Float64 // float64 - Function // function - Int // int - Int16 // int16 - Int32 // int32 - Int64 // int64 - Int8 // int8 - Interface // interface - Map // map - Pointer // pointer - Slice // slice - String // string - Struct // struct - Tuple // tuple - Uint // uint - Uint16 // uint16 - Uint32 // uint32 - Uint64 // uint64 - Uint8 // uint8 - Uintptr // uintptr - UnsafePointer // unsafe.Pointer - UntypedBool // untyped bool - UntypedComplex // untyped complex - UntypedFloat // untyped float - UntypedInt // untyped int - UntypedNil // untyped nil - UntypedRune // untyped rune - UntypedString // untyped string -) - -type typeSetter interface { - setType(t Type) Type -} - -type typeCache struct { - t Type -} - -func (n *typeCache) Type() Type { - if n.t != nil { - return n.t - } - - n.t = Invalid - return Invalid -} - -func (n *typeCache) setType(t Type) Type { - n.t = t - return t -} - -func (n *typeCache) enter(c *ctx, nd Node) bool { - switch { - case n.t == nil: - n.t = invalidRecursiveType - return true - case n.t == invalidRecursiveType: - n.t = Invalid - c.err(nd, "invalid recursive type") - return false - default: - return false - } -} - -type typer interface { - Type() Type -} - -type Type interface { - Node - - // Align returns the alignment in bytes of a value of this type when allocated - // in memory. - Align() int - - // FieldAlign returns the alignment in bytes of a value of this type when used - // as a field in a struct. - FieldAlign() int - - // Kind returns the specific kind of this type. - Kind() Kind - - // Size returns the number of bytes needed to store a value of the given type; - // it is analogous to unsafe.Sizeof. - Size() int64 - - // String returns a string representation of the type. The string - // representation is not guaranteed to be unique among types. - String() string - - check(c *ctx) Type -} - -func (n *ArrayTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *ArrayTypeNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *ArrayTypeNode) Kind() Kind { return Array } -func (n *ArrayTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *ArrayTypeNode) String() string { - return fmt.Sprintf("[%v]%v", n.ArrayLength.Value(), n.ElementType) -} - -func (n *ArrayTypeNode) check(c *ctx) Type { - if n == nil { - return Invalid - } - - n.ArrayLength = n.ArrayLength.checkExpr(c) - v := c.convertValue(n.ArrayLength, n.ArrayLength.Value(), c.cfg.int) - if !known(v) { - return Invalid - } - - n.ElementType.check(c) - return n -} - -// ChanDir represents a channel direction. -type ChanDir int - -// Values of type ChanDir. -const ( - SendRecv ChanDir = iota - SendOnly - RecvOnly -) - -func (n *ChannelTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *ChannelTypeNode) FieldAlign() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ChannelTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *ChannelTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *ChannelTypeNode) String() string { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *ChannelTypeNode) check(c *ctx) Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *FunctionTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *FunctionTypeNode) FieldAlign() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *FunctionTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *FunctionTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *FunctionTypeNode) String() string { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} -func (n *FunctionTypeNode) check(c *ctx) Type { - if !n.enter(c, n) { - if n.guard == guardChecking { - return Invalid - } - - return n - } - - defer func() { n.guard = guardChecked }() - - n.Signature.check(c) - return n -} - -func (n *InterfaceTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *InterfaceTypeNode) FieldAlign() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *InterfaceTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *InterfaceTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *InterfaceTypeNode) String() string { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} -func (n *InterfaceTypeNode) check(c *ctx) Type { - if !n.enter(c, n) { - if n.guard == guardChecking { - return Invalid - } - - return n - } - - defer func() { n.guard = guardChecked }() - - n.InterfaceElemList.check(c, n) - return n -} - -func (n *InterfaceElemListNode) check(c *ctx, t *InterfaceTypeNode) { - if n == nil { - return - } - - for l := n; l != nil; l = l.List { - l.InterfaceElem.check(c, t) - } -} - -func (n *InterfaceElemNode) check(c *ctx, t *InterfaceTypeNode) { - if n == nil { - return - } - - n.MethodElem.check(c, t) - n.TypeElem.check(c) -} - -func (n *MethodElemNode) check(c *ctx, t *InterfaceTypeNode) { - if n == nil { - return - } - - nm := n.MethodName.Src() - if ex := t.methods[nm]; ex != nil { - panic(todo("")) - } - - if t.methods == nil { - t.methods = map[string]*MethodElemNode{} - } - t.methods[nm] = n - n.typ = n.Signature.check(c) -} - -func (n *TypeElemListNode) check(c *ctx) { - if n == nil { - return - } - - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -type InvalidType struct{} - -func (n *InvalidType) Align() int { return 1 } -func (n *InvalidType) FieldAlign() int { return 1 } -func (n *InvalidType) Kind() Kind { return InvalidKind } -func (n *InvalidType) Position() (r token.Position) { return r } -func (n *InvalidType) Size() int64 { return 1 } -func (n *InvalidType) Source(full bool) string { return "" } -func (n *InvalidType) String() string { return "" } -func (n *InvalidType) check(c *ctx) Type { return n } - -func (n *MapTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *MapTypeNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *MapTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *MapTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *MapTypeNode) String() string { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *MapTypeNode) check(c *ctx) Type { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *ParenthesizedTypeNode) Align() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedTypeNode) FieldAlign() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedTypeNode) Kind() Kind { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedTypeNode) Size() int64 { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedTypeNode) String() string { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedTypeNode) check(c *ctx) Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *PointerTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *PointerTypeNode) FieldAlign() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *PointerTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *PointerTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *PointerTypeNode) String() string { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *PointerTypeNode) check(c *ctx) Type { - if !n.enter(c, n) { - if n.guard == guardChecking { - return Invalid - } - - return n - } - - defer func() { n.guard = guardChecked }() - - switch x := n.BaseType.(type) { - case *TypeNameNode: - x.checkDefined(c) - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - return n -} - -type PredeclaredType struct { - Node - kind Kind - t ABIType -} - -func (c *ctx) newPredeclaredType(n Node, kind Kind) *PredeclaredType { - t, ok := c.cfg.abi.Types[kind] - if !ok && !isAnyUntypedKind(kind) { - panic(todo("%v: internal error %s: %s", n.Position(), n.Source(false), kind)) - } - - return &PredeclaredType{ - Node: n, - kind: kind, - t: t, - } -} - -func (n *PredeclaredType) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *PredeclaredType) FieldAlign() int { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *PredeclaredType) Kind() Kind { return n.kind } -func (n *PredeclaredType) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *PredeclaredType) String() string { - switch n.Kind() { - case - String, - UntypedInt: - - return n.Kind().String() - default: - panic(todo("%v: %s %s", n.Position(), n.Kind(), n.Source(false))) - } -} - -func (n *PredeclaredType) check(c *ctx) Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *SliceTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *SliceTypeNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *SliceTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *SliceTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *SliceTypeNode) String() string { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *SliceTypeNode) check(c *ctx) Type { - if !n.enter(c, n) { - if n.guard == guardChecking { - return Invalid - } - - return n - } - - defer func() { n.guard = guardChecked }() - - switch x := n.ElementType.(type) { - case *TypeNameNode: - x.checkDefined(c) - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - return n -} - -type Field struct { - Declaration *FieldDeclNode - Name string -} - -func (n *StructTypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *StructTypeNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *StructTypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *StructTypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *StructTypeNode) String() string { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *StructTypeNode) check(c *ctx) Type { - if !n.enter(c, n) { - if n.guard == guardChecking { - return Invalid - } - - return n - } - - defer func() { n.guard = guardChecked }() - - for l := n.FieldDeclList; l != nil; l = l.List { - n.fields = append(n.fields, l.check(c)...) - } - return n -} - -func (n *FieldDeclListNode) check(c *ctx) []Field { - return n.FieldDecl.check(c) -} - -func (n *FieldDeclNode) check(c *ctx) (r []Field) { - switch { - case n.EmbeddedField != nil: - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - default: - n.TypeNode.check(c) - for l := n.IdentifierList; l != nil; l = l.List { - r = append(r, Field{n, l.IDENT.Src()}) - } - } - return r -} - -type TupleType struct { - Node - Types []Type -} - -func newTupleType(n Node, types []Type) *TupleType { return &TupleType{n, types} } - -func (n *TupleType) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TupleType) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TupleType) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *TupleType) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func (n *TupleType) Source(full bool) (r string) { - if n.Node != nil { - r = n.Node.Source(full) - } - return r -} - -func (n *TupleType) String() string { - var a []string - for _, v := range n.Types { - a = append(a, v.String()) - } - return fmt.Sprintf("(%s)", strings.Join(a, ", ")) -} - -func (n *TupleType) check(c *ctx) Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *TypeDefNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeDefNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeDefNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeDefNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeDefNode) String() string { return fmt.Sprintf("%s.%s", n.pkg.ImportPath, n.IDENT.Src()) } - -func (n *TypeDefNode) check(c *ctx) Type { - if n == nil { - return Invalid - } - - if n.pkg != nil { - return n - } - - n.pkg = c.pkg - if n.TypeParameters != nil { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - } - - switch x := n.TypeNode.check(c).(type) { - case *PredeclaredType: - n.TypeNode = x - } - return n -} - -func (n *TypeNameNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNameNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNameNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNameNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNameNode) String() string { return n.Name.Source(false) } - -func (n *TypeNameNode) checkDefined(c *ctx) bool { - switch x := n.Name.(type) { - case Token: - switch _, nmd := n.LexicalScope().lookup(x); y := nmd.n.(type) { - case *TypeDefNode, *AliasDeclNode: - return true - default: - panic(todo("%v: type=%T %s", y.Position(), y, y.Source(false))) - } - case *QualifiedIdentNode: - if !token.IsExported(x.IDENT.Src()) { - panic(todo("")) - } - - switch _, nmd := n.LexicalScope().lookup(x.PackageName); y := nmd.n.(type) { - case *ImportSpecNode: - if y.pkg == nil { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - } - - switch _, nmd := y.pkg.Scope.lookup(x.IDENT); z := nmd.n.(type) { - case *TypeDefNode, *AliasDeclNode: - return true - default: - panic(todo("%v: type=%T %s", z.Position(), z, z.Source(false))) - } - default: - panic(todo("%v: type=%T %s", y.Position(), y, y.Source(false))) - } - default: - panic(todo("%v: type=%T %s", n.Position(), x, n.Source(false))) - } -} - -func (n *TypeNameNode) check(c *ctx) Type { - if n == nil { - return Invalid - } - - switch x := n.Name.(type) { - case Token: - nm := x.Src() - if c.isBuiltin() { - switch nm { - case "bool": - return c.newPredeclaredType(n, Bool) - case "uint8": - return c.newPredeclaredType(n, Uint8) - case "uint16": - return c.newPredeclaredType(n, Uint16) - case "uint32": - return c.newPredeclaredType(n, Uint32) - case "uint64": - return c.newPredeclaredType(n, Uint64) - case "int8": - return c.newPredeclaredType(n, Int8) - case "int16": - return c.newPredeclaredType(n, Int16) - case "int32": - return c.newPredeclaredType(n, Int32) - case "int64": - return c.newPredeclaredType(n, Int64) - case "float32": - return c.newPredeclaredType(n, Float32) - case "float64": - return c.newPredeclaredType(n, Float64) - case "complex64": - return c.newPredeclaredType(n, Complex64) - case "complex128": - return c.newPredeclaredType(n, Complex128) - case "string": - return c.newPredeclaredType(n, String) - case "int": - return c.newPredeclaredType(n, Int) - case "uint": - return c.newPredeclaredType(n, Uint) - case "uintptr": - return c.newPredeclaredType(n, Uintptr) - case "Type": - // ok - default: - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - } - } - - pkg, _, nmd := c.lookup(n.LexicalScope(), x) - switch y := nmd.n.(type) { - case *TypeDefNode: - if pkg != c.pkg { - return y - } - - return y.check(c) - case nil: - panic(todo("%v: %T %s", x.Position(), y, x.Source(false))) - default: - panic(todo("%v: %T %s", y.Position(), y, y.Source(false))) - } - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } -} - -func (n *TypeNode) Align() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNode) FieldAlign() int { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNode) Kind() Kind { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNode) Size() int64 { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNode) String() string { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } -func (n *TypeNode) check(c *ctx) Type { panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) } - -func isAnyUntypedType(t Type) bool { return isAnyUntypedKind(t.Kind()) } - -func isAnyUntypedKind(k Kind) bool { - switch k { - case UntypedBool, UntypedComplex, UntypedFloat, UntypedInt, UntypedNil, UntypedRune, UntypedString: - return true - } - - return false -} - -const ( - guardUnchecked guard = iota - guardChecking - guardChecked -) - -type guard byte - -func (n *guard) enter(c *ctx, nd Node) bool { - switch *n { - case guardUnchecked: - *n = guardChecking - return true - case guardChecking: - c.err(nd, "invalid recursive type") - return false - default: - return false - } -} - -func isAnyArithmeticType(t Type) bool { return isArithmeticType(t) || isUntypedArithmeticType(t) } - -func isUntypedArithmeticType(t Type) bool { - switch t.Kind() { - case UntypedInt, UntypedFloat, UntypedComplex: - return true - default: - return false - } -} - -func isArithmeticType(t Type) bool { - return isIntegerType(t) || isFloatType(t) || isComplexType(t) -} - -func isComplexType(t Type) bool { - switch t.Kind() { - case Complex64, Complex128: - return true - default: - return false - } -} - -func isFloatType(t Type) bool { - switch t.Kind() { - case Float32, Float64: - return true - default: - return false - } -} - -func isIntegerType(t Type) bool { - switch t.Kind() { - case Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr: - return true - default: - return false - } -} - -func (c *ctx) isIdentical(n Node, t, u Type) bool { - tk := t.Kind() - uk := u.Kind() - if tk != uk { - return false - } - - if t == u { - return true - } - - if isAnyUntypedKind(tk) && isAnyUntypedKind(uk) && tk == uk { - return true - } - - switch x := t.(type) { - // case *ArrayTypeNode: - // switch y := u.(type) { - // case *ArrayTypeNode: - // return x.Len == y.Len && c.isIdentical(n, x.Elem, y.Elem) - // } - // case *StructType: - // switch y := u.(type) { - // case *StructType: - // if len(x.Fields) != len(y.Fields) { - // return false - // } - - // for i, v := range x.Fields { - // w := y.Fields[i] - // if v.Name != w.Name || !c.isIdentical(n, v.Type(), w.Type()) { - // return false - // } - // } - - // return true - // } - // case *FunctionType: - // switch y := u.(type) { - // case *FunctionType: - // in, out := x.Parameters.Types, x.Result.Types - // in2, out2 := y.Parameters.Types, y.Result.Types - // if len(in) != len(in2) || len(out) != len(out2) { - // return false - // } - - // for i, v := range in { - // if !c.isIdentical(n, v, in2[i]) { - // return false - // } - // } - - // for i, v := range out { - // if !c.isIdentical(n, v, out2[i]) { - // return false - // } - // } - - // return true - // } - // case *PointerType: - // switch y := u.(type) { - // case *PointerType: - // return c.isIdentical(n, x.Elem, y.Elem) - // } - default: - c.err(n, "TODO %v %v", x, u) - } - - return false -} - -func (c *ctx) mustIdentical(n Node, t, u Type) bool { - if !c.isIdentical(n, t, u) { - c.err(n, "incompatible types: %v and %v", t, u) - return false - } - - return true -} - -func (c *ctx) checkType(n Node) Type { - switch x := n.(type) { - case *ArrayTypeNode: - return x.check(c) - default: - c.err(n, "TODO %T", x) - return Invalid - } -} diff --git a/vendor/modernc.org/gc/v3/value.go b/vendor/modernc.org/gc/v3/value.go deleted file mode 100644 index c2cefd2fc..000000000 --- a/vendor/modernc.org/gc/v3/value.go +++ /dev/null @@ -1,716 +0,0 @@ -// Copyright 2022 The Gc Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gc // modernc.org/gc/v3 - -import ( - "go/constant" - "math" -) - -var ( - _ Expression = (*BasicLitNode)(nil) - _ Expression = (*BinaryExpressionNode)(nil) - _ Expression = (*CompositeLitNode)(nil) - _ Expression = (*ConversionNode)(nil) - _ Expression = (*FunctionLitNode)(nil) - _ Expression = (*KeyedElementNode)(nil) - _ Expression = (*LiteralValueNode)(nil) - _ Expression = (*MethodExprNode)(nil) - _ Expression = (*OperandNameNode)(nil) - _ Expression = (*OperandNode)(nil) - _ Expression = (*OperandQualifiedNameNode)(nil) - _ Expression = (*ParenthesizedExpressionNode)(nil) - _ Expression = (*PrimaryExprNode)(nil) - _ Expression = (*UnaryExprNode)(nil) - _ Expression = (*ValueExpression)(nil) - - falseVal = constant.MakeBool(false) - trueVal = constant.MakeBool(true) - unknown = constant.MakeUnknown() -) - -func known(v constant.Value) bool { return v != nil && v.Kind() != constant.Unknown } - -type valueCache struct { - v constant.Value -} - -func (n *valueCache) Value() constant.Value { - if n.v != nil { - return n.v - } - - return unknown -} - -func (n *valueCache) setValue(v constant.Value) constant.Value { - n.v = v - return v -} - -type valuer interface { - Value() constant.Value -} - -type Expression interface { - Node - checkExpr(c *ctx) Expression - clone() Expression - typer - valuer -} - -type ValueExpression struct { - Node - typeCache - valueCache -} - -func (n *ValueExpression) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ValueExpression) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *BasicLitNode) Type() Type { - switch n.Ch() { - case CHAR: - return n.ctx.int32 - case INT: - return n.ctx.untypedInt - case FLOAT: - return n.ctx.untypedFloat - case STRING: - return n.ctx.untypedString - default: - panic(todo("%v: %T %s %v", n.Position(), n, n.Source(false), n.Ch())) - } -} - -func (n *BasicLitNode) Value() constant.Value { - return constant.MakeFromLiteral(n.Src(), n.Ch(), 0) -} - -func (n *BasicLitNode) checkExpr(c *ctx) Expression { - n.ctx = c - if !known(n.Value()) { - c.err(n, "invalid literal: %s", n.Source(false)) - } - return n -} - -func (n *BasicLitNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNameNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNameNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNameNode) checkExpr(c *ctx) Expression { - in, named := n.LexicalScope().lookup(n.Name) - switch x := named.n.(type) { - case *ConstSpecNode: - switch in.kind { - case UniverseScope: - switch n.Name.Src() { - case "iota": - if c.iota < 0 { - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - - r := &ValueExpression{Node: x} - r.t = c.untypedInt - r.v = constant.MakeInt64(c.iota) - return r - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - default: - return x.Expression - } - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } -} - -func (n *OperandNameNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedExpressionNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedExpressionNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ParenthesizedExpressionNode) checkExpr(c *ctx) Expression { - return n.Expression.checkExpr(c) -} - -func (n *ParenthesizedExpressionNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *LiteralValueNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *LiteralValueNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *LiteralValueNode) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *LiteralValueNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *KeyedElementNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *KeyedElementNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *KeyedElementNode) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *KeyedElementNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *CompositeLitNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *CompositeLitNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *CompositeLitNode) checkExpr(c *ctx) Expression { - if n == nil { - return nil - } - - if !n.enter(c, n) { - return n - } - - t := n.setType(c.checkType(n.LiteralType)) - n.LiteralValue.check(c, t) - return n -} - -func (n *CompositeLitNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *LiteralValueNode) check(c *ctx, t Type) { - if n == nil { - return - } - - switch t.Kind() { - case Array: - n.checkArray(c, t.(*ArrayTypeNode)) - default: - panic(todo("%v: %T %s %v", n.Position(), n, n.Source(false), t.Kind())) - } -} - -func (n *LiteralValueNode) checkArray(c *ctx, t *ArrayTypeNode) { - panic(todo("%v: %T %s %s", n.Position(), n, t, n.Source(false))) -} - -func (n *FunctionLitNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *FunctionLitNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *FunctionLitNode) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *FunctionLitNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNode) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandQualifiedNameNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandQualifiedNameNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandQualifiedNameNode) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *OperandQualifiedNameNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *ConversionNode) Type() Type { - return n.TypeNode -} - -func (n *ConversionNode) checkExpr(c *ctx) Expression { - t := n.TypeNode.check(c) - n.Expression = n.Expression.checkExpr(c) - v := n.Expression.Value() - n.v = c.convertValue(n.Expression, v, t) - return n -} - -func (n *ConversionNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *MethodExprNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *MethodExprNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *MethodExprNode) checkExpr(c *ctx) Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *MethodExprNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *PrimaryExprNode) Type() Type { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *PrimaryExprNode) Value() constant.Value { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *PrimaryExprNode) checkExpr(c *ctx) Expression { - switch x := n.PrimaryExpr.(type) { - case *OperandNameNode: - _, named := x.LexicalScope().lookup(x.Name) - switch y := named.n.(type) { - case *TypeDefNode: - switch z := n.Postfix.(type) { - case *ArgumentsNode: - cnv := &ConversionNode{ - TypeNode: &TypeNameNode{ - Name: x.Name, - lexicalScoper: x.lexicalScoper, - }, - LPAREN: z.LPAREN, - Expression: z.Expression, - RPAREN: z.RPAREN, - } - return cnv.checkExpr(c) - default: - panic(todo("%v: %T %s", n.Position(), z, n.Source(false))) - } - default: - panic(todo("%v: %T %s", n.Position(), y, n.Source(false))) - } - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } - - n.PrimaryExpr = n.PrimaryExpr.checkExpr(c) - switch x := n.Postfix.(type) { - default: - panic(todo("%v: %T %s", n.Position(), x, n.Source(false))) - } -} - -func (n *PrimaryExprNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *BinaryExpressionNode) checkExpr(c *ctx) (r Expression) { - if n == nil { - return nil - } - - if n.typeCache.Type() != Invalid { - return n - } - - n.LHS = n.LHS.checkExpr(c) - n.RHS = n.RHS.checkExpr(c) - lv := n.LHS.Value() - lt := n.LHS.Type() - rv := n.RHS.Value() - rt := n.RHS.Type() - - defer func() { - if known(lv) && known(rv) && r != nil && !known(r.Value()) { - c.err(n.Op, "operation value not determined: %v %s %v", lv, n.Op.Src(), rv) - } - }() - - switch n.Op.Ch() { - case SHL, SHR: - var u uint64 - var uOk bool - n.t = lt - // The right operand in a shift expression must have integer type or be an - // untyped constant representable by a value of type uint. - switch { - case isIntegerType(rt): - // ok - case known(rv): - if isAnyArithmeticType(rt) { - rv = c.convertValue(n.RHS, rv, c.cfg.uint) - if known(rv) { - u, uOk = constant.Uint64Val(rv) - } - break - } - - c.err(n.Op, "TODO %v", n.Op.Src()) - return n - default: - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - return n - } - - // If the left operand of a non-constant shift expression is an untyped - // constant, it is first implicitly converted to the type it would assume if - // the shift expression were replaced by its left operand alone. - switch { - case known(lv) && !known(rv): - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - // c.err(n.Op, "TODO %v", n.Op.Ch.str()) - // return n - case known(lv) && known(rv): - if !uOk { - panic(todo("")) - } - - n.t = lt - n.v = constant.Shift(lv, n.Op.Ch(), uint(u)) - default: - trc("", known(lv), known(rv), u, uOk) - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) - // n.t = lt - // n.v = constant.BinaryOp(lv, n.Op.Ch(), rv) - } - case ADD, SUB, MUL, QUO, REM: - if !isAnyArithmeticType(lt) || !isAnyArithmeticType(rt) { - c.err(n.Op, "TODO %v %v", lt, rt) - break - } - - // For other binary operators, the operand types must be identical unless the - // operation involves shifts or untyped constants. - // - // Except for shift operations, if one operand is an untyped constant and the - // other operand is not, the constant is implicitly converted to the type of - // the other operand. - switch { - case isAnyUntypedType(lt) && isAnyUntypedType(rt): - n.v = constant.BinaryOp(lv, n.Op.Ch(), rv) - switch n.v.Kind() { - case constant.Int: - n.t = c.untypedInt - case constant.Float: - n.t = c.untypedFloat - default: - c.err(n.Op, "TODO %v %v %q %v %v -> %v %v", lv, lt, n.Op.Src(), rv, rt, n.v, n.v.Kind()) - } - case isAnyUntypedType(lt) && !isAnyUntypedType(rt): - c.err(n.Op, "TODO %v %v %q %v %v", lv, lt, n.Op.Src(), rv, rt) - case !isAnyUntypedType(lt) && isAnyUntypedType(rt): - c.err(n.Op, "TODO %v %v %q %v %v", lv, lt, n.Op.Src(), rv, rt) - default: // case !isAnyUntypedType(lt) && !isAnyUntypedType(rt): - c.err(n.Op, "TODO %v %v %q %v %v", lv, lt, n.Op.Src(), rv, rt) - } - default: - c.err(n.Op, "TODO %v %v %q %v %v", lv, lt, n.Op.Src(), rv, rt) - } - return n -} - -func (n *BinaryExpressionNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (n *UnaryExprNode) checkExpr(c *ctx) Expression { - if n == nil { - return nil - } - - if n.typeCache.Type() != Invalid { - return n - } - - n.UnaryExpr = n.UnaryExpr.checkExpr(c) - v := n.UnaryExpr.Value() - t := n.UnaryExpr.Type() - switch n.Op.Ch() { - default: - trc("", v, t) - panic(todo("%v: %T %s", n.Op.Position(), n, n.Source(false))) - } -} - -func (n *UnaryExprNode) clone() Expression { - panic(todo("%v: %T %s", n.Position(), n, n.Source(false))) -} - -func (c *ctx) convertValue(n Node, v constant.Value, to Type) (r constant.Value) { - if !known(v) { - return unknown - } - - switch to.Kind() { - case - Complex128, - Complex64, - Function, - Interface, - Map, - Pointer, - Slice, - String, - Struct, - Tuple, - UnsafePointer, - UntypedBool, - UntypedComplex, - UntypedFloat, - UntypedInt, - UntypedNil, - UntypedRune, - UntypedString: - - c.err(n, "TODO %v -> %v", v, to) - case Int: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - i64, ok := constant.Int64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - switch c.cfg.goarch { - case "386", "arm": - if i64 < math.MinInt32 || i64 > math.MaxInt32 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - } - return w - case Int8: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - i64, ok := constant.Int64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - if i64 < math.MinInt8 || i64 > math.MaxInt8 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Int16: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - i64, ok := constant.Int64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - if i64 < math.MinInt16 || i64 > math.MaxInt16 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Int32: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - i64, ok := constant.Int64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - if i64 < math.MinInt32 || i64 > math.MaxInt32 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Int64: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - if _, ok := constant.Int64Val(w); !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Uint, Uintptr: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - u64, ok := constant.Uint64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - switch c.cfg.goarch { - case "386", "arm": - if u64 > math.MaxUint32 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - } - return w - case Uint8: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - u64, ok := constant.Uint64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - if u64 > math.MaxUint8 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Uint16: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - u64, ok := constant.Uint64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - if u64 > math.MaxUint16 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Uint32: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - u64, ok := constant.Uint64Val(w) - if !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - if u64 > math.MaxUint32 { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Uint64: - w := constant.ToInt(v) - if !known(w) { - c.err(n, "cannot convert %s to %s", v, to) - return unknown - } - - if _, ok := constant.Uint64Val(w); !ok { - c.err(n, "value %s overflows %s", v, to) - return unknown - } - - return w - case Float32, Float64: - return constant.ToFloat(v) - case Bool: - if v.Kind() == constant.Bool { - return v - } - } - return unknown -} diff --git a/vendor/modernc.org/sqlite/Makefile b/vendor/modernc.org/sqlite/Makefile index 8b7472ddd..e98811c34 100644 --- a/vendor/modernc.org/sqlite/Makefile +++ b/vendor/modernc.org/sqlite/Makefile @@ -37,8 +37,8 @@ build_all_targets: GOOS=linux GOARCH=riscv64 go build -v ./... GOOS=linux GOARCH=s390x go test -c -o /dev/null GOOS=linux GOARCH=s390x go build -v ./... - GOOS=netbsd GOARCH=amd64 go test -c -o /dev/null - GOOS=netbsd GOARCH=amd64 go build -v ./... + # GOOS=netbsd GOARCH=amd64 go test -c -o /dev/null + # GOOS=netbsd GOARCH=amd64 go build -v ./... GOOS=openbsd GOARCH=amd64 go test -c -o /dev/null GOOS=openbsd GOARCH=amd64 go build -v ./... GOOS=openbsd GOARCH=arm64 go test -c -o /dev/null @@ -69,7 +69,10 @@ test: go test -v -timeout 24h 2>&1 | tee log-test vendor: - go run vendor_libsqlite3.go && make build_all_targets + cd vendor_libsqlite3 && go build -o ../vendor main.go + ./vendor + rm -f vendor + make build_all_targets make build_all_targets work: diff --git a/vendor/modernc.org/sqlite/lib/hooks.go b/vendor/modernc.org/sqlite/lib/hooks.go index 9bedb87ac..4bd919b89 100644 --- a/vendor/modernc.org/sqlite/lib/hooks.go +++ b/vendor/modernc.org/sqlite/lib/hooks.go @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !(linux && arm64) + package sqlite3 import ( @@ -12,3 +14,7 @@ func X__ccgo_sqlite3_log(t *libc.TLS, iErrCode int32, zFormat uintptr, va uintptr) { /* sqlite3.c:29405:17: */ libc.X__ccgo_sqlite3_log(t, iErrCode, zFormat, va) } + +func PatchIssue199() { + // nop +} diff --git a/vendor/modernc.org/sqlite/lib/hooks_linux_arm64.go b/vendor/modernc.org/sqlite/lib/hooks_linux_arm64.go new file mode 100644 index 000000000..be3873bf9 --- /dev/null +++ b/vendor/modernc.org/sqlite/lib/hooks_linux_arm64.go @@ -0,0 +1,30 @@ +// Copyright 2019 The Sqlite Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package sqlite3 + +import ( + "syscall" + "unsafe" + + "modernc.org/libc" +) + +// Format and write a message to the log if logging is enabled. +func X__ccgo_sqlite3_log(t *libc.TLS, iErrCode int32, zFormat uintptr, va uintptr) { /* sqlite3.c:29405:17: */ + libc.X__ccgo_sqlite3_log(t, iErrCode, zFormat, va) +} + +// https://gitlab.com/cznic/sqlite/-/issues/199 +// +// We are currently stuck on libc@v1.55.3. Until that is resolved - fix the +// problem at runtime. +func PatchIssue199() { + p := unsafe.Pointer(&_aSyscall) + *(*uintptr)(unsafe.Add(p, 608)) = __ccgo_fp(_unixGetpagesizeIssue199) +} + +func _unixGetpagesizeIssue199(tls *libc.TLS) (r int32) { + return int32(syscall.Getpagesize()) +} diff --git a/vendor/modernc.org/sqlite/sqlite.go b/vendor/modernc.org/sqlite/sqlite.go index 1af3eea7b..1e7e437ab 100644 --- a/vendor/modernc.org/sqlite/sqlite.go +++ b/vendor/modernc.org/sqlite/sqlite.go @@ -55,6 +55,11 @@ sqliteLockedSharedcache = sqlite3.SQLITE_LOCKED | (1 << 8) ) +// https://gitlab.com/cznic/sqlite/-/issues/199 +func init() { + sqlite3.PatchIssue199() +} + // Error represents sqlite library error code. type Error struct { msg string diff --git a/vendor/modernc.org/sqlite/vendor_libsqlite3.go b/vendor/modernc.org/sqlite/vendor_libsqlite3.go deleted file mode 100644 index d7190ec4d..000000000 --- a/vendor/modernc.org/sqlite/vendor_libsqlite3.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2024 The Sqlite Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build none -// +build none - -// Tool for 1.28+ -> 1.29+. Pulls adjusted libsqlite3 code to this repo. - -package main - -import ( - "bytes" - "fmt" - "go/token" - "os" - "path/filepath" - "strings" - - "modernc.org/gc/v3" -) - -func fail(rc int, msg string, args ...any) { - fmt.Fprintln(os.Stderr, strings.TrimSpace(fmt.Sprintf(msg, args...))) - os.Exit(rc) -} - -func main() { - for _, v := range []struct{ goos, goarch string }{ - {"darwin", "amd64"}, - {"darwin", "arm64"}, - {"freebsd", "amd64"}, - {"freebsd", "arm64"}, - {"linux", "386"}, - {"linux", "amd64"}, - {"linux", "arm"}, - {"linux", "arm64"}, - {"linux", "loong64"}, - {"linux", "ppc64le"}, - {"linux", "riscv64"}, - {"linux", "s390x"}, - {"windows", "386"}, - {"windows", "amd64"}, - } { - base := fmt.Sprintf("ccgo_%s_%s.go", v.goos, v.goarch) - if v.goos == "windows" && v.goarch == "amd64" { - base = "ccgo_windows.go" - } - ifn := filepath.Join("..", "libsqlite3", base) - fmt.Printf("%s/%s\t%s\n", v.goos, v.goarch, ifn) - in, err := os.ReadFile(ifn) - if err != nil { - fail(1, "%s\n", err) - } - - ast, err := gc.ParseFile(ifn, in) - if err != nil { - fail(1, "%s\n", err) - } - - b := bytes.NewBuffer(nil) - s := ast.SourceFile.PackageClause.Source(true) - s = strings.Replace(s, "package libsqlite3", "package sqlite3", 1) - fmt.Fprintln(b, s) - fmt.Fprint(b, ast.SourceFile.ImportDeclList.Source(true)) - taken := map[string]struct{}{} - for n := ast.SourceFile.TopLevelDeclList; n != nil; n = n.List { - switch x := n.TopLevelDecl.(type) { - case *gc.TypeDeclNode: - adn := x.TypeSpecList.TypeSpec.(*gc.AliasDeclNode) - nm := adn.IDENT.Src() - taken[nm] = struct{}{} - } - } - loop: - for n := ast.SourceFile.TopLevelDeclList; n != nil; n = n.List { - switch x := n.TopLevelDecl.(type) { - case *gc.ConstDeclNode: - switch y := x.ConstSpec.(type) { - case *gc.ConstSpecNode: - if y.IDENT.Src() != "SQLITE_TRANSIENT" { - fmt.Fprintln(b, x.Source(true)) - } - default: - panic(fmt.Sprintf("%v: %T %q", x.Position(), y, x.Source(false))) - } - - case *gc.FunctionDeclNode: - fmt.Fprintln(b, x.Source(true)) - case *gc.TypeDeclNode: - fmt.Fprintln(b, x.Source(true)) - adn := x.TypeSpecList.TypeSpec.(*gc.AliasDeclNode) - nm := adn.IDENT.Src() - nm2 := nm[1:] - if _, ok := taken[nm2]; ok { - break - } - - if token.IsExported(nm) { - fmt.Fprintf(b, "\ntype %s = %s\n", nm2, nm) - } - case *gc.VarDeclNode: - fmt.Fprintln(b, x.Source(true)) - default: - fmt.Printf("%v: TODO %T\n", n.Position(), x) - break loop - } - } - - b.WriteString(` -type Sqlite3_int64 = sqlite3_int64 -type Sqlite3_mutex_methods = sqlite3_mutex_methods -type Sqlite3_value = sqlite3_value - -type Sqlite3_index_info = sqlite3_index_info -type Sqlite3_module = sqlite3_module -type Sqlite3_vtab = sqlite3_vtab -type Sqlite3_vtab_cursor = sqlite3_vtab_cursor - -`) - base = strings.Replace(base, "ccgo_", "sqlite_", 1) - if err := os.WriteFile(filepath.Join("lib", base), b.Bytes(), 0660); err != nil { - fail(1, "%s\n", err) - } - } -} diff --git a/vendor/modernc.org/strutil/AUTHORS b/vendor/modernc.org/strutil/AUTHORS deleted file mode 100644 index d04c45011..000000000 --- a/vendor/modernc.org/strutil/AUTHORS +++ /dev/null @@ -1,12 +0,0 @@ -# This file lists authors for copyright purposes. This file is distinct from -# the CONTRIBUTORS files. See the latter for an explanation. -# -# Names should be added to this file as: -# Name or Organization -# -# The email address is not required for organizations. -# -# Please keep the list sorted. - -CZ.NIC z.s.p.o. -Jan Mercl <0xjnml@gmail.com> diff --git a/vendor/modernc.org/strutil/CONTRIBUTORS b/vendor/modernc.org/strutil/CONTRIBUTORS deleted file mode 100644 index 5e86f0607..000000000 --- a/vendor/modernc.org/strutil/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -# This file lists people who contributed code to this repository. The AUTHORS -# file lists the copyright holders; this file lists people. -# -# Names should be added to this file like so: -# Name -# -# Please keep the list sorted. - -Jan Mercl <0xjnml@gmail.com> diff --git a/vendor/modernc.org/strutil/LICENSE b/vendor/modernc.org/strutil/LICENSE deleted file mode 100644 index 2fdd92cf7..000000000 --- a/vendor/modernc.org/strutil/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2014 The strutil Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the names of the authors nor the names of the -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/modernc.org/strutil/Makefile b/vendor/modernc.org/strutil/Makefile deleted file mode 100644 index d19e2d70b..000000000 --- a/vendor/modernc.org/strutil/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2014 The sortutil Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -.PHONY: all clean cover cpu editor internalError later mem nuke todo edit - -grep=--include=*.go --include=*.l --include=*.y --include=*.yy -ngrep='TODOOK\|parser\.go\|scanner\.go\|.*_string\.go' - -all: editor - go vet 2>&1 | grep -v $(ngrep) || true - golint 2>&1 | grep -v $(ngrep) || true - make todo - unused . || true - misspell *.go - gosimple || true - maligned || true - unconvert -apply - -clean: - go clean - rm -f *~ *.test *.out - -cover: - t=$(shell tempfile) ; go test -coverprofile $$t && go tool cover -html $$t && unlink $$t - -cpu: clean - go test -run @ -bench . -cpuprofile cpu.out - go tool pprof -lines *.test cpu.out - -edit: - @ 1>/dev/null 2>/dev/null gvim -p Makefile *.go - -editor: - unconvert -apply || true - gofmt -l -s -w *.go - go test -i - go test 2>&1 | tee log - go install - -internalError: - egrep -ho '"internal error.*"' *.go | sort | cat -n - -later: - @grep -n $(grep) LATER * || true - @grep -n $(grep) MAYBE * || true - -mem: clean - go test -run @ -bench . -memprofile mem.out -memprofilerate 1 -timeout 24h - go tool pprof -lines -web -alloc_space *.test mem.out - -nuke: clean - go clean -i - -todo: - @grep -nr $(grep) ^[[:space:]]*_[[:space:]]*=[[:space:]][[:alpha:]][[:alnum:]]* * | grep -v $(ngrep) || true - @grep -nr $(grep) TODO * | grep -v $(ngrep) || true - @grep -nr $(grep) BUG * | grep -v $(ngrep) || true - @grep -nr $(grep) [^[:alpha:]]println * | grep -v $(ngrep) || true diff --git a/vendor/modernc.org/strutil/README b/vendor/modernc.org/strutil/README deleted file mode 100644 index 0ace6534a..000000000 --- a/vendor/modernc.org/strutil/README +++ /dev/null @@ -1,8 +0,0 @@ -modernc.orgall-able mirror of modified code already published at: -http://git.nic.cz/redmine/projects/gostrutil/repository - -Online godoc documentation for this package (should be) available at: -http://gopkgdoc.appspot.com/pkg/modernc.org/strutil - -Installation: -$ go get modernc.org/strutil diff --git a/vendor/modernc.org/strutil/strutil.go b/vendor/modernc.org/strutil/strutil.go deleted file mode 100644 index 7d07b7994..000000000 --- a/vendor/modernc.org/strutil/strutil.go +++ /dev/null @@ -1,733 +0,0 @@ -// Copyright (c) 2014 The sortutil Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package strutil collects utils supplemental to the standard strings package. -package strutil // import "modernc.org/strutil" - -import ( - "bytes" - "encoding/base32" - "encoding/base64" - "fmt" - "io" - "os" - "path/filepath" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" -) - -// Base32ExtDecode decodes base32 extended (RFC 4648) text to binary data. -func Base32ExtDecode(text []byte) (data []byte, err error) { - n := base32.HexEncoding.DecodedLen(len(text)) - data = make([]byte, n) - decoder := base32.NewDecoder(base32.HexEncoding, bytes.NewBuffer(text)) - if n, err = decoder.Read(data); err != nil { - n = 0 - } - data = data[:n] - return -} - -// Base32ExtEncode encodes binary data to base32 extended (RFC 4648) encoded text. -func Base32ExtEncode(data []byte) (text []byte) { - n := base32.HexEncoding.EncodedLen(len(data)) - buf := bytes.NewBuffer(make([]byte, 0, n)) - encoder := base32.NewEncoder(base32.HexEncoding, buf) - encoder.Write(data) - encoder.Close() - if buf.Len() != n { - panic("internal error") - } - return buf.Bytes() -} - -// Base64Decode decodes base64 text to binary data. -func Base64Decode(text []byte) (data []byte, err error) { - n := base64.StdEncoding.DecodedLen(len(text)) - data = make([]byte, n) - decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewBuffer(text)) - if n, err = decoder.Read(data); err != nil { - n = 0 - } - data = data[:n] - return -} - -// Base64Encode encodes binary data to base64 encoded text. -func Base64Encode(data []byte) (text []byte) { - n := base64.StdEncoding.EncodedLen(len(data)) - buf := bytes.NewBuffer(make([]byte, 0, n)) - encoder := base64.NewEncoder(base64.StdEncoding, buf) - encoder.Write(data) - encoder.Close() - if buf.Len() != n { - panic("internal error") - } - return buf.Bytes() -} - -// Formatter is an io.Writer extended by a fmt.Printf like function Format -type Formatter interface { - io.Writer - Format(format string, args ...interface{}) (n int, errno error) -} - -type indentFormatter struct { - io.Writer - indent []byte - indentLevel int - state int -} - -const ( - st0 = iota - stBOL - stPERC - stBOLPERC -) - -// IndentFormatter returns a new Formatter which interprets %i and %u in the -// Format() format string as indent and undent commands. The commands can -// nest. The Formatter writes to io.Writer 'w' and inserts one 'indent' -// string per current indent level value. -// Behaviour of commands reaching negative indent levels is undefined. -// IndentFormatter(os.Stdout, "\t").Format("abc%d%%e%i\nx\ny\n%uz\n", 3) -// output: -// abc3%e -// x -// y -// z -// The Go quoted string literal form of the above is: -// "abc%%e\n\tx\n\tx\nz\n" -// The commands can be scattered between separate invocations of Format(), -// i.e. the formatter keeps track of the indent level and knows if it is -// positioned on start of a line and should emit indentation(s). -// The same output as above can be produced by e.g.: -// f := IndentFormatter(os.Stdout, " ") -// f.Format("abc%d%%e%i\nx\n", 3) -// f.Format("y\n%uz\n") -func IndentFormatter(w io.Writer, indent string) Formatter { - return &indentFormatter{w, []byte(indent), 0, stBOL} -} - -func (f *indentFormatter) format(flat bool, format string, args ...interface{}) (n int, errno error) { - buf := []byte{} - for i := 0; i < len(format); i++ { - c := format[i] - switch f.state { - case st0: - switch c { - case '\n': - cc := c - if flat && f.indentLevel != 0 { - cc = ' ' - } - buf = append(buf, cc) - f.state = stBOL - case '%': - f.state = stPERC - default: - buf = append(buf, c) - } - case stBOL: - switch c { - case '\n': - cc := c - if flat && f.indentLevel != 0 { - cc = ' ' - } - buf = append(buf, cc) - case '%': - f.state = stBOLPERC - default: - if !flat { - for i := 0; i < f.indentLevel; i++ { - buf = append(buf, f.indent...) - } - } - buf = append(buf, c) - f.state = st0 - } - case stBOLPERC: - switch c { - case 'i': - f.indentLevel++ - f.state = stBOL - case 'u': - f.indentLevel-- - f.state = stBOL - default: - if !flat { - for i := 0; i < f.indentLevel; i++ { - buf = append(buf, f.indent...) - } - } - buf = append(buf, '%', c) - f.state = st0 - } - case stPERC: - switch c { - case 'i': - f.indentLevel++ - f.state = st0 - case 'u': - f.indentLevel-- - f.state = st0 - default: - buf = append(buf, '%', c) - f.state = st0 - } - default: - panic("unexpected state") - } - } - switch f.state { - case stPERC, stBOLPERC: - buf = append(buf, '%') - } - return f.Write([]byte(fmt.Sprintf(string(buf), args...))) -} - -func (f *indentFormatter) Format(format string, args ...interface{}) (n int, errno error) { - return f.format(false, format, args...) -} - -type flatFormatter indentFormatter - -// FlatFormatter returns a newly created Formatter with the same functionality as the one returned -// by IndentFormatter except it allows a newline in the 'format' string argument of Format -// to pass through iff indent level is currently zero. -// -// If indent level is non-zero then such new lines are changed to a space character. -// There is no indent string, the %i and %u format verbs are used solely to determine the indent level. -// -// The FlatFormatter is intended for flattening of normally nested structure textual representation to -// a one top level structure per line form. -// FlatFormatter(os.Stdout, " ").Format("abc%d%%e%i\nx\ny\n%uz\n", 3) -// output in the form of a Go quoted string literal: -// "abc3%%e x y z\n" -func FlatFormatter(w io.Writer) Formatter { - return (*flatFormatter)(IndentFormatter(w, "").(*indentFormatter)) -} - -func (f *flatFormatter) Format(format string, args ...interface{}) (n int, errno error) { - return (*indentFormatter)(f).format(true, format, args...) -} - -// Pool handles aligning of strings having equal values to the same string instance. -// Intended use is to conserve some memory e.g. where a large number of identically valued strings -// with non identical backing arrays may exists in several semantically distinct instances of some structs. -// Pool is *not* concurrent access safe. It doesn't handle common prefix/suffix aligning, -// e.g. having s1 == "abc" and s2 == "bc", s2 is not automatically aligned as s1[1:]. -type Pool struct { - pool map[string]string -} - -// NewPool returns a newly created Pool. -func NewPool() *Pool { - return &Pool{map[string]string{}} -} - -// Align returns a string with the same value as its argument. It guarantees that -// all aligned strings share a single instance in memory. -func (p *Pool) Align(s string) string { - if a, ok := p.pool[s]; ok { - return a - } - - s = StrPack(s) - p.pool[s] = s - return s -} - -// Count returns the number of items in the pool. -func (p *Pool) Count() int { - return len(p.pool) -} - -// GoPool is a concurrent access safe version of Pool. -type GoPool struct { - pool map[string]string - rwm *sync.RWMutex -} - -// NewGoPool returns a newly created GoPool. -func NewGoPool() (p *GoPool) { - return &GoPool{map[string]string{}, &sync.RWMutex{}} -} - -// Align returns a string with the same value as its argument. It guarantees that -// all aligned strings share a single instance in memory. -func (p *GoPool) Align(s string) (y string) { - if s != "" { - p.rwm.RLock() // R++ - if a, ok := p.pool[s]; ok { // found - p.rwm.RUnlock() // R-- - return a - } - - p.rwm.RUnlock() // R-- - // not found but with a race condition, retry within a write lock - p.rwm.Lock() // W++ - defer p.rwm.Unlock() // W-- - if a, ok := p.pool[s]; ok { // done in a race - return a - } - - // we won - s = StrPack(s) - p.pool[s] = s - return s - } - - return -} - -// Count returns the number of items in the pool. -func (p *GoPool) Count() int { - return len(p.pool) -} - -// Dict is a string <-> id bijection. Dict is *not* concurrent access safe for assigning new ids -// to strings not yet contained in the bijection. -// Id for an empty string is guaranteed to be 0, -// thus Id for any non empty string is guaranteed to be non zero. -type Dict struct { - si map[string]int - is []string -} - -// NewDict returns a newly created Dict. -func NewDict() (d *Dict) { - d = &Dict{map[string]int{}, []string{}} - d.Id("") - return -} - -// Count returns the number of items in the dict. -func (d *Dict) Count() int { - return len(d.is) -} - -// Id maps string s to its numeric identificator. -func (d *Dict) Id(s string) (y int) { - if y, ok := d.si[s]; ok { - return y - } - - s = StrPack(s) - y = len(d.is) - d.si[s] = y - d.is = append(d.is, s) - return -} - -// S maps an id to its string value and ok == true. Id values not contained in the bijection -// return "", false. -func (d *Dict) S(id int) (s string, ok bool) { - if id >= len(d.is) { - return "", false - } - return d.is[id], true -} - -// GoDict is a concurrent access safe version of Dict. -type GoDict struct { - si map[string]int - is []string - rwm *sync.RWMutex -} - -// NewGoDict returns a newly created GoDict. -func NewGoDict() (d *GoDict) { - d = &GoDict{map[string]int{}, []string{}, &sync.RWMutex{}} - d.Id("") - return -} - -// Count returns the number of items in the dict. -func (d *GoDict) Count() int { - return len(d.is) -} - -// Id maps string s to its numeric identificator. The implementation honors getting -// an existing id at the cost of assigning a new one. -func (d *GoDict) Id(s string) (y int) { - d.rwm.RLock() // R++ - if y, ok := d.si[s]; ok { // found - d.rwm.RUnlock() // R-- - return y - } - - d.rwm.RUnlock() // R-- - - // not found but with a race condition - d.rwm.Lock() // W++ recheck with write lock - defer d.rwm.Unlock() // W-- - if y, ok := d.si[s]; ok { // some other goroutine won already - return y - } - - // a race free not found state => insert the string - s = StrPack(s) - y = len(d.is) - d.si[s] = y - d.is = append(d.is, s) - return -} - -// S maps an id to its string value and ok == true. Id values not contained in the bijection -// return "", false. -func (d *GoDict) S(id int) (s string, ok bool) { - d.rwm.RLock() // R++ - defer d.rwm.RUnlock() // R-- - if id >= len(d.is) { - return "", false - } - return d.is[id], true -} - -// StrPack returns a new instance of s which is tightly packed in memory. -// It is intended for avoiding the situation where having a live reference -// to a string slice over an unreferenced biger underlying string keeps the biger one -// in memory anyway - it can't be GCed. -func StrPack(s string) string { - return string([]byte(s)) // T(U(T)) intentional. -} - -// JoinFields returns strings in flds joined by sep. Flds may contain arbitrary -// bytes, including the sep as they are safely escaped. JoinFields panics if -// sep is the backslash character or if len(sep) != 1. -func JoinFields(flds []string, sep string) string { - if len(sep) != 1 || sep == "\\" { - panic("invalid separator") - } - - a := make([]string, len(flds)) - for i, v := range flds { - v = strings.Replace(v, "\\", "\\0", -1) - a[i] = strings.Replace(v, sep, "\\1", -1) - } - return strings.Join(a, sep) -} - -// SplitFields splits s, which must be produced by JoinFields using the same -// sep, into flds. SplitFields panics if sep is the backslash character or if -// len(sep) != 1. -func SplitFields(s, sep string) (flds []string) { - if len(sep) != 1 || sep == "\\" { - panic("invalid separator") - } - - a := strings.Split(s, sep) - r := make([]string, len(a)) - for i, v := range a { - v = strings.Replace(v, "\\1", sep, -1) - r[i] = strings.Replace(v, "\\0", "\\", -1) - } - return r -} - -// PrettyPrintHooks allow to customize the result of PrettyPrint for types -// listed in the map value. -type PrettyPrintHooks map[reflect.Type]func(f Formatter, v interface{}, prefix, suffix string) - -// PrettyString returns the output of PrettyPrint as a string. -func PrettyString(v interface{}, prefix, suffix string, hooks PrettyPrintHooks) string { - var b bytes.Buffer - PrettyPrint(&b, v, prefix, suffix, hooks) - return b.String() -} - -// PrettyPrint pretty prints v to w. Zero values and unexported struct fields -// are omitted. -// -// Force printing of zero values of struct fields by including in the field tag -// PrettyPrint:"zero". -// -// Enable using a String method, if any, of a struct field type by including in -// the field tag PrettyPrint:"stringer". -// -// The tags can be combined as in PrettyPrint:"zero,stringer". The order is not -// important, so PrettyPrint:stringer,zero has the same effect. -// -// A hook attached to the field type has priority over the struct field tag -// described above. -func PrettyPrint(w io.Writer, v interface{}, prefix, suffix string, hooks PrettyPrintHooks) { - if v == nil { - return - } - - f := IndentFormatter(w, "· ") - - defer func() { - if e := recover(); e != nil { - f.Format("\npanic: %v", e) - } - }() - - prettyPrint(nil, f, prefix, suffix, v, hooks, false, false) -} - -func prettyPrint(protect map[interface{}]struct{}, sf Formatter, prefix, suffix string, v interface{}, hooks PrettyPrintHooks, zero, stringer bool) { - if v == nil { - return - } - - rt := reflect.TypeOf(v) - if handler := hooks[rt]; handler != nil { - handler(sf, v, prefix, suffix) - return - } - - rv := reflect.ValueOf(v) - if stringer { - if _, ok := v.(fmt.Stringer); ok { - sf.Format("%s%s", prefix, v) - sf.Format(suffix) - return - } - } - - switch rt.Kind() { - case reflect.Slice: - if rv.Len() == 0 && !zero { - return - } - - sf.Format("%s[]%T{ // len %d%i\n", prefix, rv.Index(0).Interface(), rv.Len()) - for i := 0; i < rv.Len(); i++ { - prettyPrint(protect, sf, fmt.Sprintf("%d: ", i), ",\n", rv.Index(i).Interface(), hooks, false, false) - } - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%u}" + suffix) - case reflect.Array: - if reflect.Zero(rt).Interface() == rv.Interface() && !zero { - return - } - - sf.Format("%s[%d]%T{%i\n", prefix, rv.Len(), rv.Index(0).Interface()) - for i := 0; i < rv.Len(); i++ { - prettyPrint(protect, sf, fmt.Sprintf("%d: ", i), ",\n", rv.Index(i).Interface(), hooks, false, false) - } - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%u}" + suffix) - case reflect.Struct: - if rt.NumField() == 0 { - return - } - - if reflect.DeepEqual(reflect.Zero(rt).Interface(), rv.Interface()) && !zero { - return - } - - sf.Format("%s%T{%i\n", prefix, v) - for i := 0; i < rt.NumField(); i++ { - f := rv.Field(i) - if !f.CanInterface() { - continue - } - - var stringer, zero bool - ft := rt.Field(i) - if tag, ok := ft.Tag.Lookup("PrettyPrint"); ok { - a := strings.Split(tag, ",") - for _, v := range a { - switch strings.TrimSpace(v) { - case "stringer": - stringer = true - case "zero": - zero = true - } - } - } - prettyPrint(protect, sf, fmt.Sprintf("%s: ", rt.Field(i).Name), ",\n", f.Interface(), hooks, zero, stringer) - } - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%u}" + suffix) - case reflect.Ptr: - if rv.IsNil() && !zero { - return - } - - rvi := rv.Interface() - if _, ok := protect[rvi]; ok { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s&%T{ /* recursive/repetitive pointee not shown */ }"+suffix, prefix, rv.Elem().Interface()) - return - } - - if protect == nil { - protect = map[interface{}]struct{}{} - } - protect[rvi] = struct{}{} - prettyPrint(protect, sf, prefix+"&", suffix, rv.Elem().Interface(), hooks, false, false) - case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8: - if v := rv.Int(); v != 0 || zero { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%v"+suffix, prefix, v) - } - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8: - if v := rv.Uint(); v != 0 || zero { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%v"+suffix, prefix, v) - } - case reflect.Float32, reflect.Float64: - if v := rv.Float(); v != 0 || zero { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%v"+suffix, prefix, v) - } - case reflect.Complex64, reflect.Complex128: - if v := rv.Complex(); v != 0 || zero { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%v"+suffix, prefix, v) - } - case reflect.Uintptr: - if v := rv.Uint(); v != 0 || zero { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%v"+suffix, prefix, v) - } - case reflect.UnsafePointer: - s := fmt.Sprintf("%p", rv.Interface()) - if s == "0x0" && !zero { - return - } - - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%s"+suffix, prefix, s) - case reflect.Bool: - if v := rv.Bool(); v || zero { - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%v"+suffix, prefix, rv.Bool()) - } - case reflect.String: - s := rv.Interface().(string) - if s == "" && !zero { - return - } - - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%q"+suffix, prefix, s) - case reflect.Chan: - if reflect.Zero(rt).Interface() == rv.Interface() && !zero { - return - } - - c := rv.Cap() - s := "" - if c != 0 { - s = fmt.Sprintf("// capacity: %d", c) - } - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%s%s %s%s"+suffix, prefix, rt.ChanDir(), rt.Elem().Name(), s) - case reflect.Func: - if rv.IsNil() && !zero { - return - } - - var in, out []string - for i := 0; i < rt.NumIn(); i++ { - x := reflect.Zero(rt.In(i)) - in = append(in, fmt.Sprintf("%T", x.Interface())) - } - if rt.IsVariadic() { - i := len(in) - 1 - in[i] = "..." + in[i][2:] - } - for i := 0; i < rt.NumOut(); i++ { - out = append(out, rt.Out(i).Name()) - } - s := "(" + strings.Join(in, ", ") + ")" - t := strings.Join(out, ", ") - if len(out) > 1 { - t = "(" + t + ")" - } - if t != "" { - t = " " + t - } - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%sfunc%s%s { ... }"+suffix, prefix, s, t) - case reflect.Map: - keys := rv.MapKeys() - if len(keys) == 0 && !zero { - return - } - - var buf bytes.Buffer - nf := IndentFormatter(&buf, "· ") - var skeys []string - for i, k := range keys { - prettyPrint(protect, nf, "", "", k.Interface(), hooks, false, false) - skeys = append(skeys, fmt.Sprintf("%s%10d", buf.Bytes(), i)) - buf.Reset() - } - sort.Strings(skeys) - sf.Format("%s%T{%i\n", prefix, v) - for _, k := range skeys { - si := strings.TrimSpace(k[len(k)-10:]) - k = k[:len(k)-10] - n, _ := strconv.ParseUint(si, 10, 64) - mv := rv.MapIndex(keys[n]) - prettyPrint(protect, sf, fmt.Sprintf("%s: ", k), ",\n", mv.Interface(), hooks, false, false) - } - suffix = strings.Replace(suffix, "%", "%%", -1) - sf.Format("%u}" + suffix) - } -} - -// Gopath returns the value of the $GOPATH environment variable or its default -// value if not set. -func Gopath() string { - if r := os.Getenv("GOPATH"); r != "" { - return r - } - - // go1.8: https://github.com/golang/go/blob/74628a8b9f102bddd5078ee426efe0fd57033115/doc/code.html#L122 - switch runtime.GOOS { - case "plan9": - return os.Getenv("home") - case "windows": - return filepath.Join(os.Getenv("USERPROFILE"), "go") - default: - return filepath.Join(os.Getenv("HOME"), "go") - } -} - -// Homepath returns the user's home directory path. -func Homepath() string { - // go1.8: https://github.com/golang/go/blob/74628a8b9f102bddd5078ee426efe0fd57033115/doc/code.html#L122 - switch runtime.GOOS { - case "plan9": - return os.Getenv("home") - case "windows": - return os.Getenv("USERPROFILE") - default: - return os.Getenv("HOME") - } -} - -// ImportPath returns the import path of the caller or an error, if any. -func ImportPath() (string, error) { - _, file, _, ok := runtime.Caller(1) - if !ok { - return "", fmt.Errorf("runtime.Caller failed") - } - - gopath := Gopath() - for _, v := range filepath.SplitList(gopath) { - gp := filepath.Join(v, "src") - path, err := filepath.Rel(gp, file) - if err != nil { - continue - } - - return filepath.Dir(path), nil - } - - return "", fmt.Errorf("cannot determine import path using GOPATH=%s", gopath) -} diff --git a/vendor/modernc.org/token/LICENSE b/vendor/modernc.org/token/LICENSE deleted file mode 100644 index 6a66aea5e..000000000 --- a/vendor/modernc.org/token/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/modernc.org/token/Makefile b/vendor/modernc.org/token/Makefile deleted file mode 100644 index be445590e..000000000 --- a/vendor/modernc.org/token/Makefile +++ /dev/null @@ -1,56 +0,0 @@ -.PHONY: all clean cover cpu editor internalError later mem nuke todo edit - -grep=--include=*.go --include=*.l --include=*.y --include=*.yy -ngrep='TODOOK\|parser\.go\|scanner\.go\|.*_string\.go' - -all: editor - go vet 2>&1 | grep -v $(ngrep) || true - golint 2>&1 | grep -v $(ngrep) || true - make todo - unused . || true - misspell *.go - gosimple || true - maligned || true - unconvert -apply - -clean: - go clean - rm -f *~ *.test *.out - -cover: - t=$(shell mktemp) ; go test -coverprofile $$t && go tool cover -html $$t && unlink $$t - -cpu: clean - go test -run @ -bench . -cpuprofile cpu.out - go tool pprof -lines *.test cpu.out - - -edit: - @touch log - @if [ -f "Session.vim" ]; then gvim -S & else gvim -p Makefile *.go & fi - -editor: - gofmt -l -s -w *.go - go test -i - go test 2>&1 | tee log - go install - -internalError: - egrep -ho '"internal error.*"' *.go | sort | cat -n - -later: - @grep -n $(grep) LATER * || true - @grep -n $(grep) MAYBE * || true - -mem: clean - go test -run @ -bench . -memprofile mem.out -memprofilerate 1 -timeout 24h - go tool pprof -lines -web -alloc_space *.test mem.out - -nuke: clean - go clean -i - -todo: - @grep -nr $(grep) ^[[:space:]]*_[[:space:]]*=[[:space:]][[:alpha:]][[:alnum:]]* * | grep -v $(ngrep) || true - @grep -nr $(grep) TODO * | grep -v $(ngrep) || true - @grep -nr $(grep) BUG * | grep -v $(ngrep) || true - @grep -nr $(grep) [^[:alpha:]]println * | grep -v $(ngrep) || true diff --git a/vendor/modernc.org/token/README.md b/vendor/modernc.org/token/README.md deleted file mode 100644 index d13c2d1fa..000000000 --- a/vendor/modernc.org/token/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# token - -Package token is a variant of the stdlib package token with types FileSet and Token removed - -Installation - - $ go get [-u] modernc.org/token - -Documentation: [godoc.org/modernc.org/token](http://godoc.org/modernc.org/token) diff --git a/vendor/modernc.org/token/position.go b/vendor/modernc.org/token/position.go deleted file mode 100644 index 57895ad6e..000000000 --- a/vendor/modernc.org/token/position.go +++ /dev/null @@ -1,359 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package token is variant of the stdlib package token with types FileSet and -// Token removed. -package token // import "modernc.org/token" - -import ( - "fmt" - "sort" -) - -// ----------------------------------------------------------------------------- -// Positions - -// Position describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -type Position struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (byte count) -} - -// IsValid reports whether the position is valid. -func (pos *Position) IsValid() bool { return pos.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// file:line valid position with file name but no column (column == 0) -// line:column valid position without file name -// line valid position without file name and no column (column == 0) -// file invalid position with file name -// - invalid position without file name -func (pos Position) String() string { - s := pos.Filename - if pos.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d", pos.Line) - if pos.Column != 0 { - s += fmt.Sprintf(":%d", pos.Column) - } - } - if s == "" { - s = "-" - } - return s -} - -// Pos is a compact encoding of a source position within a file set. -// It can be converted into a Position for a more convenient, but much -// larger, representation. -// -// The Pos value for a given file is a number in the range [base, base+size], -// where base and size are specified when a file is added to the file set. -// The difference between a Pos value and the corresponding file base -// corresponds to the byte offset of that position (represented by the Pos value) -// from the beginning of the file. Thus, the file base offset is the Pos value -// representing the first byte in the file. -// -// To create the Pos value for a specific source offset (measured in bytes), -// first add the respective file to the current file set using FileSet.AddFile -// and then call File.Pos(offset) for that file. Given a Pos value p -// for a specific file set fset, the corresponding Position value is -// obtained by calling fset.Position(p). -// -// Pos values can be compared directly with the usual comparison operators: -// If two Pos values p and q are in the same file, comparing p and q is -// equivalent to comparing the respective source file offsets. If p and q -// are in different files, p < q is true if the file implied by p was added -// to the respective file set before the file implied by q. -type Pos int - -// The zero value for Pos is NoPos; there is no file and line information -// associated with it, and NoPos.IsValid() is false. NoPos is always -// smaller than any other Pos value. The corresponding Position value -// for NoPos is the zero value for Position. -const NoPos Pos = 0 - -// IsValid reports whether the position is valid. -func (p Pos) IsValid() bool { - return p != NoPos -} - -// ----------------------------------------------------------------------------- -// File - -// A File is a handle for a file belonging to a FileSet. -// A File has a name, size, and line offset table. -type File struct { - name string // file name as provided to AddFile - base int // Pos value range for this file is [base...base+size] - size int // file size as provided to AddFile - - lines []int // lines contains the offset of the first character for each line (the first entry is always 0) - infos []lineInfo -} - -// NewFile returns a new file with a given filename and file size. -// -func NewFile(filename string, size int) *File { - return &File{name: filename, base: 1, size: size, lines: []int{0}} -} - -// Name returns the file name of file f as registered with AddFile. -func (f *File) Name() string { - return f.name -} - -// Base returns the base offset of file f as registered with AddFile. -func (f *File) Base() int { - return f.base -} - -// Size returns the size of file f as registered with AddFile. -func (f *File) Size() int { - return f.size -} - -// LineCount returns the number of lines in file f. -func (f *File) LineCount() int { - n := len(f.lines) - return n -} - -// AddLine adds the line offset for a new line. -// The line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise the line offset is ignored. -func (f *File) AddLine(offset int) { - if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { - f.lines = append(f.lines, offset) - } -} - -// MergeLine merges a line with the following line. It is akin to replacing -// the newline character at the end of the line with a space (to not change the -// remaining offsets). To obtain the line number, consult e.g. Position.Line. -// MergeLine will panic if given an invalid line number. -func (f *File) MergeLine(line int) { - if line < 1 { - panic(fmt.Sprintf("invalid line number %d (should be >= 1)", line)) - } - if line >= len(f.lines) { - panic(fmt.Sprintf("invalid line number %d (should be < %d)", line, len(f.lines))) - } - // To merge the line numbered with the line numbered , - // we need to remove the entry in lines corresponding to the line - // numbered . The entry in lines corresponding to the line - // numbered is located at index , since indices in lines - // are 0-based and line numbers are 1-based. - copy(f.lines[line:], f.lines[line+1:]) - f.lines = f.lines[:len(f.lines)-1] -} - -// SetLines sets the line offsets for a file and reports whether it succeeded. -// The line offsets are the offsets of the first character of each line; -// for instance for the content "ab\nc\n" the line offsets are {0, 3}. -// An empty file has an empty line offset table. -// Each line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise SetLines fails and returns -// false. -// Callers must not mutate the provided slice after SetLines returns. -func (f *File) SetLines(lines []int) bool { - // verify validity of lines table - size := f.size - for i, offset := range lines { - if i > 0 && offset <= lines[i-1] || size <= offset { - return false - } - } - - // set lines table - f.lines = lines - return true -} - -// SetLinesForContent sets the line offsets for the given file content. -// It ignores position-altering //line comments. -func (f *File) SetLinesForContent(content []byte) { - var lines []int - line := 0 - for offset, b := range content { - if line >= 0 { - lines = append(lines, line) - } - line = -1 - if b == '\n' { - line = offset + 1 - } - } - - // set lines table - f.lines = lines -} - -// LineStart returns the Pos value of the start of the specified line. -// It ignores any alternative positions set using AddLineColumnInfo. -// LineStart panics if the 1-based line number is invalid. -func (f *File) LineStart(line int) Pos { - if line < 1 { - panic(fmt.Sprintf("invalid line number %d (should be >= 1)", line)) - } - if line > len(f.lines) { - panic(fmt.Sprintf("invalid line number %d (should be < %d)", line, len(f.lines))) - } - return Pos(f.base + f.lines[line-1]) -} - -// A lineInfo object describes alternative file, line, and column -// number information (such as provided via a //line directive) -// for a given file offset. -type lineInfo struct { - // fields are exported to make them accessible to gob - Offset int - Filename string - Line, Column int -} - -// AddLineInfo is like AddLineColumnInfo with a column = 1 argument. -// It is here for backward-compatibility for code prior to Go 1.11. -func (f *File) AddLineInfo(offset int, filename string, line int) { - f.AddLineColumnInfo(offset, filename, line, 1) -} - -// AddLineColumnInfo adds alternative file, line, and column number -// information for a given file offset. The offset must be larger -// than the offset for the previously added alternative line info -// and smaller than the file size; otherwise the information is -// ignored. -// -// AddLineColumnInfo is typically used to register alternative position -// information for line directives such as //line filename:line:column. -func (f *File) AddLineColumnInfo(offset int, filename string, line, column int) { - if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size { - f.infos = append(f.infos, lineInfo{offset, filename, line, column}) - } -} - -// Pos returns the Pos value for the given file offset; -// the offset must be <= f.Size(). -// f.Pos(f.Offset(p)) == p. -func (f *File) Pos(offset int) Pos { - if offset > f.size { - panic(fmt.Sprintf("invalid file offset %d (should be <= %d)", offset, f.size)) - } - return Pos(f.base + offset) -} - -// Offset returns the offset for the given file position p; -// p must be a valid Pos value in that file. -// f.Offset(f.Pos(offset)) == offset. -func (f *File) Offset(p Pos) int { - if int(p) < f.base || int(p) > f.base+f.size { - panic(fmt.Sprintf("invalid Pos value %d (should be in [%d, %d])", p, f.base, f.base+f.size)) - } - return int(p) - f.base -} - -// Line returns the line number for the given file position p; -// p must be a Pos value in that file or NoPos. -func (f *File) Line(p Pos) int { - return f.Position(p).Line -} - -func searchLineInfos(a []lineInfo, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1 -} - -// unpack returns the filename and line and column number for a file offset. -// If adjusted is set, unpack will return the filename and line information -// possibly adjusted by //line comments; otherwise those comments are ignored. -func (f *File) unpack(offset int, adjusted bool) (filename string, line, column int) { - filename = f.name - if i := searchInts(f.lines, offset); i >= 0 { - line, column = i+1, offset-f.lines[i]+1 - } - if adjusted && len(f.infos) > 0 { - // few files have extra line infos - if i := searchLineInfos(f.infos, offset); i >= 0 { - alt := &f.infos[i] - filename = alt.Filename - if i := searchInts(f.lines, alt.Offset); i >= 0 { - // i+1 is the line at which the alternative position was recorded - d := line - (i + 1) // line distance from alternative position base - line = alt.Line + d - if alt.Column == 0 { - // alternative column is unknown => relative column is unknown - // (the current specification for line directives requires - // this to apply until the next PosBase/line directive, - // not just until the new newline) - column = 0 - } else if d == 0 { - // the alternative position base is on the current line - // => column is relative to alternative column - column = alt.Column + (offset - alt.Offset) - } - } - } - } - return -} - -func (f *File) position(p Pos, adjusted bool) (pos Position) { - offset := int(p) - f.base - pos.Offset = offset - pos.Filename, pos.Line, pos.Column = f.unpack(offset, adjusted) - return -} - -// PositionFor returns the Position value for the given file position p. -// If adjusted is set, the position may be adjusted by position-altering -// //line comments; otherwise those comments are ignored. -// p must be a Pos value in f or NoPos. -func (f *File) PositionFor(p Pos, adjusted bool) (pos Position) { - if p != NoPos { - if int(p) < f.base || int(p) > f.base+f.size { - panic(fmt.Sprintf("invalid Pos value %d (should be in [%d, %d])", p, f.base, f.base+f.size)) - } - pos = f.position(p, adjusted) - } - return -} - -// Position returns the Position value for the given file position p. -// Calling f.Position(p) is equivalent to calling f.PositionFor(p, true). -func (f *File) Position(p Pos) (pos Position) { - return f.PositionFor(p, true) -} - -// ----------------------------------------------------------------------------- -// Helper functions - -func searchInts(a []int, x int) int { - // This function body is a manually inlined version of: - // - // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1 - // - // With better compiler optimizations, this may not be needed in the - // future, but at the moment this change improves the go/printer - // benchmark performance by ~30%. This has a direct impact on the - // speed of gofmt and thus seems worthwhile (2011-04-29). - // TODO(gri): Remove this when compilers have caught up. - i, j := 0, len(a) - for i < j { - h := int(uint(i+j) >> 1) // avoid overflow when computing h - // i ≤ h < j - if a[h] <= x { - i = h + 1 - } else { - j = h - } - } - return i - 1 -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 5e333c148..ea48db0fb 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -364,11 +364,6 @@ github.com/gorilla/websocket github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities -# github.com/hashicorp/golang-lru/v2 v2.0.7 -## explicit; go 1.18 -github.com/hashicorp/golang-lru/v2 -github.com/hashicorp/golang-lru/v2/internal -github.com/hashicorp/golang-lru/v2/simplelru # github.com/hashicorp/hcl v1.0.0 ## explicit github.com/hashicorp/hcl @@ -1289,9 +1284,6 @@ gopkg.in/yaml.v2 # gopkg.in/yaml.v3 v3.0.1 ## explicit gopkg.in/yaml.v3 -# modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 -## explicit; go 1.20 -modernc.org/gc/v3 # modernc.org/libc v1.55.3 ## explicit; go 1.20 modernc.org/libc @@ -1326,21 +1318,15 @@ modernc.org/mathutil # modernc.org/memory v1.8.0 ## explicit; go 1.18 modernc.org/memory -# modernc.org/sqlite v0.0.0-00010101000000-000000000000 => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.2-concurrency-workaround +# modernc.org/sqlite v0.0.0-00010101000000-000000000000 => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.5-concurrency-workaround ## explicit; go 1.21 modernc.org/sqlite modernc.org/sqlite/lib -# modernc.org/strutil v1.2.0 -## explicit; go 1.18 -modernc.org/strutil -# modernc.org/token v1.1.0 -## explicit -modernc.org/token # mvdan.cc/xurls/v2 v2.6.0 ## explicit; go 1.22.0 mvdan.cc/xurls/v2 # github.com/go-swagger/go-swagger => github.com/superseriousbusiness/go-swagger v0.31.0-gts-go1.23-fix -# modernc.org/sqlite => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.2-concurrency-workaround +# modernc.org/sqlite => gitlab.com/NyaaaWhatsUpDoc/sqlite v1.34.5-concurrency-workaround # go.opentelemetry.io/otel => go.opentelemetry.io/otel v1.29.0 # go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.29.0 # go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.29.0