Skip to content

Use ordered maps for options and users #370

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions internal/collections/ordered_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package collections

import (
"bytes"
"encoding"
"encoding/json"
"errors"
"fmt"
"iter"
"maps"
"reflect"
"slices"
"strconv"

json2 "github.com./go-json-experiment/json"
"github.com./go-json-experiment/json/jsontext"
Expand Down Expand Up @@ -105,6 +107,10 @@ func (m *OrderedMap[K, V]) Delete(key K) (V, bool) {
// A slice of the keys can be obtained by calling `slices.Collect`.
func (m *OrderedMap[K, V]) Keys() iter.Seq[K] {
return func(yield func(K) bool) {
if m == nil {
return
}

// We use a for loop here to ensure we enumerate new items added during iteration.
//nolint:intrange
for i := 0; i < len(m.keys); i++ {
Expand All @@ -119,6 +125,10 @@ func (m *OrderedMap[K, V]) Keys() iter.Seq[K] {
// A slice of the values can be obtained by calling `slices.Collect`.
func (m *OrderedMap[K, V]) Values() iter.Seq[V] {
return func(yield func(V) bool) {
if m == nil {
return
}

// We use a for loop here to ensure we enumerate new items added during iteration.
//nolint:intrange
for i := 0; i < len(m.keys); i++ {
Expand All @@ -132,6 +142,10 @@ func (m *OrderedMap[K, V]) Values() iter.Seq[V] {
// Entries returns an iterator over the key-value pairs in the map.
func (m *OrderedMap[K, V]) Entries() iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
if m == nil {
return
}

// We use a for loop here to ensure we enumerate new items added during iteration.
//nolint:intrange
for i := 0; i < len(m.keys); i++ {
Expand All @@ -153,11 +167,19 @@ func (m *OrderedMap[K, V]) Clear() {

// Size returns the number of key-value pairs in the map.
func (m *OrderedMap[K, V]) Size() int {
if m == nil {
return 0
}

return len(m.keys)
}

// Clone returns a shallow copy of the map.
func (m *OrderedMap[K, V]) Clone() *OrderedMap[K, V] {
if m == nil {
return nil
}

m2 := m.clone()
return &m2
}
Expand All @@ -169,6 +191,59 @@ func (m *OrderedMap[K, V]) clone() OrderedMap[K, V] {
}
}

func (m OrderedMap[K, V]) MarshalJSON() ([]byte, error) {
if len(m.mp) == 0 {
return []byte("{}"), nil
}
var buf bytes.Buffer
buf.WriteByte('{')
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)

for i, k := range m.keys {
if i > 0 {
buf.WriteByte(',')
}

keyString, err := resolveKeyName(reflect.ValueOf(k))
if err != nil {
return nil, err
}

if err := enc.Encode(keyString); err != nil {
return nil, err
}

buf.WriteByte(':')

if err := enc.Encode(m.mp[k]); err != nil {
return nil, err
}
}
buf.WriteByte('}')
return buf.Bytes(), nil
}

func resolveKeyName(k reflect.Value) (string, error) {
if k.Kind() == reflect.String {
return k.String(), nil
}
if tm, ok := k.Interface().(encoding.TextMarshaler); ok {
if k.Kind() == reflect.Pointer && k.IsNil() {
return "", nil
}
buf, err := tm.MarshalText()
return string(buf), err
}
switch k.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(k.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(k.Uint(), 10), nil
}
panic("unexpected map key type")
}

func (m *OrderedMap[K, V]) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
// By convention, to approximate the behavior of Unmarshal itself,
Expand Down
14 changes: 7 additions & 7 deletions internal/compiler/module/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,7 @@ func (r *resolutionState) tryLoadModuleUsingOptionalResolutionSettings() *resolv
}

func (r *resolutionState) tryLoadModuleUsingPathsIfEligible() *resolved {
if len(r.compilerOptions.Paths) > 0 && !tspath.PathIsRelative(r.name) {
if r.compilerOptions.Paths.Size() > 0 && !tspath.PathIsRelative(r.name) {
if r.resolver.traceEnabled() {
r.resolver.host.Trace(diagnostics.X_paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0.Format(r.name))
}
Expand All @@ -1045,13 +1045,13 @@ func (r *resolutionState) tryLoadModuleUsingPathsIfEligible() *resolved {
)
}

func (r *resolutionState) tryLoadModuleUsingPaths(extensions extensions, moduleName string, containingDirectory string, paths map[string][]string, pathPatterns parsedPatterns, loader resolutionKindSpecificLoader, onlyRecordFailures bool) *resolved {
func (r *resolutionState) tryLoadModuleUsingPaths(extensions extensions, moduleName string, containingDirectory string, paths *collections.OrderedMap[string, []string], pathPatterns parsedPatterns, loader resolutionKindSpecificLoader, onlyRecordFailures bool) *resolved {
if matchedPattern := matchPatternOrExact(pathPatterns, moduleName); matchedPattern.IsValid() {
matchedStar := matchedPattern.MatchedText(moduleName)
if r.resolver.traceEnabled() {
r.resolver.host.Trace(diagnostics.Module_name_0_matched_pattern_1.Format(moduleName, matchedPattern.Text))
}
for _, subst := range paths[matchedPattern.Text] {
for _, subst := range paths.GetOrZero(matchedPattern.Text) {
path := strings.Replace(subst, "*", matchedStar, 1)
candidate := tspath.NormalizePath(tspath.CombinePaths(containingDirectory, path))
if r.resolver.traceEnabled() {
Expand Down Expand Up @@ -1688,7 +1688,7 @@ func moveToNextDirectorySeparatorIfAvailable(path string, prevSeparatorIndex int
}

func getPathsBasePath(options *core.CompilerOptions, currentDirectory string) string {
if len(options.Paths) == 0 {
if options.Paths.Size() == 0 {
return ""
}
if options.PathsBasePath != "" {
Expand All @@ -1702,12 +1702,12 @@ type parsedPatterns struct {
patterns []core.Pattern
}

func tryParsePatterns(paths map[string][]string) parsedPatterns {
func tryParsePatterns(paths *collections.OrderedMap[string, []string]) parsedPatterns {
// !!! TS has a weakmap cache
// We could store a cache on Resolver, but maybe we can wait and profile
matchableStringSet := collections.OrderedSet[string]{}
patterns := make([]core.Pattern, 0, len(paths))
for path := range paths {
patterns := make([]core.Pattern, 0, paths.Size())
for path := range paths.Keys() {
if pattern := core.TryParsePattern(path); pattern.IsValid() {
if pattern.StarIndex == -1 {
matchableStringSet.Add(path)
Expand Down
12 changes: 7 additions & 5 deletions internal/compiler/packagejson/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,33 +70,35 @@ func (p *PackageJson) GetVersionPaths(trace func(string)) VersionPaths {
type VersionPaths struct {
Version string
pathsJSON *collections.OrderedMap[string, JSONValue]
paths map[string][]string
paths *collections.OrderedMap[string, []string]
}

func (v *VersionPaths) Exists() bool {
return v != nil && v.Version != "" && v.pathsJSON != nil
}

func (v *VersionPaths) GetPaths() map[string][]string {
func (v *VersionPaths) GetPaths() *collections.OrderedMap[string, []string] {
if !v.Exists() {
return nil
}
if v.paths != nil {
return v.paths
}
v.paths = make(map[string][]string, v.pathsJSON.Size())
paths := collections.NewOrderedMapWithSizeHint[string, []string](v.pathsJSON.Size())
for key, value := range v.pathsJSON.Entries() {
if value.Type != JSONValueTypeArray {
continue
}
v.paths[key] = make([]string, len(value.AsArray()))
slice := make([]string, len(value.AsArray()))
for i, path := range value.AsArray() {
if path.Type != JSONValueTypeString {
continue
}
v.paths[key][i] = path.Value.(string)
slice[i] = path.Value.(string)
}
v.paths.Set(key, slice)
}
v.paths = paths
return v.paths
}

Expand Down
Loading
Loading