Skip to content

Commit

Permalink
Merge pull request #5 from golang-malawi/feat/dart-gen
Browse files Browse the repository at this point in the history
feat: support generating Dart classes via 11wizards/go-to-dart
  • Loading branch information
zikani03 authored Mar 2, 2024
2 parents 1b8ae16 + 9f9c117 commit 300769f
Show file tree
Hide file tree
Showing 22 changed files with 1,033 additions and 6 deletions.
1 change: 1 addition & 0 deletions 11wizards/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This directory contains a slightly modified version of [https://github.com/11wizards/go-to-dart](https://github.com/11wizards/go-to-dart) intended to be embedded in geneveev.
2 changes: 2 additions & 0 deletions 11wizards/go-to-dart/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea
dist/
21 changes: 21 additions & 0 deletions 11wizards/go-to-dart/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 11Wizards (U.K.) Limited.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
62 changes: 62 additions & 0 deletions 11wizards/go-to-dart/generator/class.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package generator

import (
"fmt"
"go/types"
"io"

"github.com/golang-malawi/geneveev/11wizards/go-to-dart/generator/format"
"github.com/golang-malawi/geneveev/11wizards/go-to-dart/generator/options"
"github.com/openconfig/goyang/pkg/indent"
)

func generateFields(wr io.Writer, st *types.Struct, registry *format.TypeFormatterRegistry, mode options.Mode) {
for i := 0; i < st.NumFields(); i++ {
field := st.Field(i)
tag := st.Tag(i)
generateFieldDeclaration(wr, field, tag, registry, mode)
fmt.Fprintln(wr, ";")
}
fmt.Fprintln(wr)
}

func generateConstructor(wr io.Writer, ts *types.TypeName, st *types.Struct, registry *format.TypeFormatterRegistry) {
fmt.Fprintf(wr, "%s({\n", ts.Name())

for i := 0; i < st.NumFields(); i++ {
f := st.Field(i)
generateFieldConstrutor(indent.NewWriter(wr, "\t"), f, registry)
fmt.Fprintln(wr, ",")
}

fmt.Fprintf(wr, "});")
fmt.Fprintln(wr)
fmt.Fprintln(wr)
}

func generateSerialization(wr io.Writer, ts *types.TypeName) {
fmt.Fprintf(wr, "Map<String, dynamic> toJson() => _$%sToJson(this);\n\n", ts.Name())
}

func generateDeserialization(wr io.Writer, ts *types.TypeName) {
fmt.Fprintf(wr, "factory %s.fromJson(Map<String, dynamic> json) => _$%sFromJson(json);\n", ts.Name(), ts.Name())
}

func generateDartClass(outputFile io.Writer, ts *types.TypeName, st *types.Struct, registry *format.TypeFormatterRegistry, mode options.Mode) {
fmt.Fprintln(outputFile, "@JsonSerializable(explicitToJson: true)")
if mode == options.Firestore {
fmt.Fprintln(outputFile, "@_TimestampConverter()")
}

fmt.Fprintf(outputFile, "class %s {\n", ts.Name())

wr := indent.NewWriter(outputFile, "\t")

generateFields(wr, st, registry, mode)
generateConstructor(wr, ts, st, registry)
generateSerialization(wr, ts)
generateDeserialization(wr, ts)

fmt.Fprintln(outputFile, "}")
fmt.Fprintln(outputFile, "")
}
9 changes: 9 additions & 0 deletions 11wizards/go-to-dart/generator/dart/timestamp_converter.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class _TimestampConverter implements JsonConverter<DateTime, Timestamp> {
const _TimestampConverter();

@override
DateTime fromJson(Timestamp json) => json.toDate();

@override
Timestamp toJson(DateTime object) => Timestamp.fromDate(object);
}
66 changes: 66 additions & 0 deletions 11wizards/go-to-dart/generator/field.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package generator

import (
"fmt"
"go/types"
"io"
"slices"

"github.com/golang-malawi/geneveev/11wizards/go-to-dart/generator/format"
"github.com/golang-malawi/geneveev/11wizards/go-to-dart/generator/options"
)

func generateFieldJSONKey(writer io.Writer, f *types.Var, tag string, registry *format.TypeFormatterRegistry, mode options.Mode) format.TypeFormatter {
formatter := registry.GetTypeFormatter(f.Type())
fieldName := format.GetFieldName(f)
jsonFieldName := format.GetJSONFieldName(tag, mode)

keyProperties := map[string]string{}

if jsonFieldName != "" && jsonFieldName != fieldName {
keyProperties["name"] = fmt.Sprintf("\"%s\"", jsonFieldName)
} else if jsonFieldName == "" {
keyProperties["name"] = fmt.Sprintf("\"%s\"", f.Name())
}

if formatter.DefaultValue(f.Type()) != "" {
keyProperties["defaultValue"] = formatter.DefaultValue(f.Type())
}

if len(keyProperties) > 0 {
fmt.Fprint(writer, "@JsonKey(")
first := true

keys := make([]string, 0)
for key, _ := range keyProperties {
keys = append(keys, key)
}
slices.Sort(keys)

for _, key := range keys {
value := keyProperties[key]

if !first {
fmt.Fprint(writer, ", ")
} else {
first = false
}

fmt.Fprintf(writer, "%s: %s", key, value)
}

fmt.Fprintf(writer, ")")

}
return formatter
}

func generateFieldDeclaration(writer io.Writer, f *types.Var, tag string, registry *format.TypeFormatterRegistry, mode options.Mode) {
formatter := generateFieldJSONKey(writer, f, tag, registry, mode)
fmt.Fprintf(writer, "final %s", formatter.Declaration(format.GetFieldName(f), f.Type()))
}

func generateFieldConstrutor(writer io.Writer, f *types.Var, registry *format.TypeFormatterRegistry) {
formatter := registry.GetTypeFormatter(f.Type())
fmt.Fprint(writer, formatter.Constructor(format.GetFieldName(f), f.Type()))
}
40 changes: 40 additions & 0 deletions 11wizards/go-to-dart/generator/format/alias.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package format

import (
"fmt"
"go/types"
)

type AliasFormatter struct {
TypeFormatterBase
}

func (f *AliasFormatter) under(expr types.Type) types.Type {
if namedType, ok := expr.(*types.Named); ok {
return namedType.Underlying()
}

return expr
}

func (f *AliasFormatter) CanFormat(expr types.Type) bool {
return f.under(expr) != nil
}

func (f *AliasFormatter) Signature(expr types.Type) string {
u := f.under(expr)
return f.Registry.GetTypeFormatter(u).Signature(u)
}

func (f *AliasFormatter) DefaultValue(_ types.Type) string {
return ""
}

func (f *AliasFormatter) Declaration(fieldName string, expr types.Type) string {
return fmt.Sprintf("%s %s", f.Signature(expr), fieldName)
}

func (f *AliasFormatter) Constructor(fieldName string, expr types.Type) string {
u := f.under(expr)
return f.Registry.GetTypeFormatter(u).Constructor(fieldName, u)
}
39 changes: 39 additions & 0 deletions 11wizards/go-to-dart/generator/format/array.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package format

import (
"fmt"
"go/types"
)

type ArrayFormatter struct {
TypeFormatterBase
}

func (f *ArrayFormatter) under(expr types.Type) (TypeFormatter, types.Type) {
sliceExpr := expr.(*types.Slice)
elem := sliceExpr.Elem()
formatter := f.Registry.GetTypeFormatter(elem)
return formatter, elem
}

func (f *ArrayFormatter) CanFormat(expr types.Type) bool {
_, ok := expr.(*types.Slice)
return ok
}

func (f *ArrayFormatter) Signature(expr types.Type) string {
formatter, expr := f.under(expr)
return fmt.Sprintf("List<%s>", formatter.Signature(expr))
}

func (f *ArrayFormatter) DefaultValue(expr types.Type) string {
return fmt.Sprintf("<%s>[]", f.Signature(expr))
}

func (f *ArrayFormatter) Declaration(fieldName string, expr types.Type) string {
return fmt.Sprintf("%s %s", f.Signature(expr), fieldName)
}

func (f *ArrayFormatter) Constructor(fieldName string, _ types.Type) string {
return "required this." + fieldName
}
55 changes: 55 additions & 0 deletions 11wizards/go-to-dart/generator/format/format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package format

import (
"fmt"
"go/types"

"github.com/golang-malawi/geneveev/11wizards/go-to-dart/generator/options"
)

type TypeFormatter interface {
SetRegistry(registry *TypeFormatterRegistry)
CanFormat(expr types.Type) bool
Signature(expr types.Type) string
DefaultValue(expr types.Type) string
Declaration(fieldName string, expr types.Type) string
Constructor(fieldName string, expr types.Type) string
}

type TypeFormatterBase struct {
Registry *TypeFormatterRegistry
Mode options.Mode
}

func (t *TypeFormatterBase) SetRegistry(registry *TypeFormatterRegistry) {
t.Registry = registry
}

type TypeFormatterRegistry struct {
KnownTypes map[types.Type]struct{}
Formatters []TypeFormatter
}

func NewTypeFormatterRegistry() *TypeFormatterRegistry {
return &TypeFormatterRegistry{
KnownTypes: make(map[types.Type]struct{}),
Formatters: make([]TypeFormatter, 0),
}
}
func (t *TypeFormatterRegistry) RegisterTypeFormatter(formatter TypeFormatter) {
t.Formatters = append(t.Formatters, formatter)
formatter.SetRegistry(t)
}

func (t *TypeFormatterRegistry) GetTypeFormatter(expr types.Type) TypeFormatter {
// walks the t.Formatters in reverse order
// so that the last registered formatter is the first to be checked
for i := len(t.Formatters) - 1; i >= 0; i-- {
f := t.Formatters[i]
if f.CanFormat(expr) {
return f
}
}

panic(fmt.Sprintf("no formatter found for %v", expr))
}
38 changes: 38 additions & 0 deletions 11wizards/go-to-dart/generator/format/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package format

import (
"fmt"
"go/types"
"reflect"
"strings"

"github.com/golang-malawi/geneveev/11wizards/go-to-dart/generator/options"
"github.com/iancoleman/strcase"
)

func GetFieldName(f *types.Var) string {
if f.Anonymous() {
panic(fmt.Sprintf("no name for field: %#v", f))
}

return strcase.ToLowerCamel(f.Name())
}

func GetJSONFieldName(tag string, mode options.Mode) string {
var tagName string
if mode == options.Firestore {
tagName = "firestore"
} else {
tagName = "json"
}

if tag != "" {
val := reflect.StructTag(strings.Trim(tag, "`"))
value, ok := val.Lookup(tagName)
if ok {
return strings.Split(value, ",")[0]
}
}

return ""
}
40 changes: 40 additions & 0 deletions 11wizards/go-to-dart/generator/format/map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package format

import (
"fmt"
"go/types"
)

type MapFormatter struct {
TypeFormatterBase
}

func (f *MapFormatter) under(expr types.Type) (TypeFormatter, TypeFormatter, types.Type, types.Type) {
mapExpr := expr.(*types.Map)
keyFormatter := f.Registry.GetTypeFormatter(mapExpr.Key())
valueFormatter := f.Registry.GetTypeFormatter(mapExpr.Elem())
return keyFormatter, valueFormatter, mapExpr.Key(), mapExpr.Elem()
}

func (f *MapFormatter) CanFormat(expr types.Type) bool {
_, ok := expr.(*types.Map)
return ok
}

func (f *MapFormatter) Signature(expr types.Type) string {
keyFormatter, valueFormatter, keyExpr, valueExpr := f.under(expr)
return fmt.Sprintf("Map<%s, %s>", keyFormatter.Signature(keyExpr), valueFormatter.Signature(valueExpr))
}

func (f *MapFormatter) DefaultValue(expr types.Type) string {
keyFormatter, valueFormatter, keyExpr, valueExpr := f.under(expr)
return fmt.Sprintf("<%s, %s>{}", keyFormatter.Signature(keyExpr), valueFormatter.Signature(valueExpr))
}

func (f *MapFormatter) Declaration(fieldName string, expr types.Type) string {
return fmt.Sprintf("%s %s", f.Signature(expr), fieldName)
}

func (f *MapFormatter) Constructor(fieldName string, _ types.Type) string {
return "required this." + fieldName
}
Loading

0 comments on commit 300769f

Please sign in to comment.