Codegen for enum types

This generates a flow type for enums:

```noms
enum Handedness {
  right
  left
  switch
}
```

Generates

```js
type E =
  0 |  // right
  1 |  // left
  2;  // switch
```

Issue #1081
This commit is contained in:
Erik Arvidsson
2016-04-04 14:35:37 -07:00
parent d1a6fbe0c7
commit 1014573c7e
7 changed files with 29 additions and 5 deletions

View File

@@ -10,6 +10,7 @@ package code
import (
"fmt"
"reflect"
"strings"
"unicode"
@@ -447,6 +448,11 @@ func (gen Generator) ToTypeJS(t types.Type, fileID, nomsName string, indent int)
panic("Unreachable")
}
// IsLast determines if |index| is the last index in |seq|.
func (gen Generator) IsLast(index int, seq interface{}) bool {
return reflect.ValueOf(seq).Len() == index+1
}
// ToTag replaces "-" characters in s with "_", so it can be used in a Go identifier.
// TODO: replace other illegal chars as well?
func ToTag(r ref.Ref) string {

View File

@@ -280,6 +280,7 @@ func (gen *codeGen) readTemplates() *template.Template {
"valueToDef": gen.generator.ValueToDef,
"valueToUser": gen.generator.ValueToUser,
"valueZero": gen.generator.ValueZero,
"isLast": gen.generator.IsLast,
}).ParseGlob(glob))
}

View File

@@ -1 +1,3 @@
// enum.tmpl
{{$name := .Name}}
export type {{.Name}} ={{range $index, $id := .Ids}}
{{$index}}{{if isLast $index $.Ids | not}} |{{else}};{{end}} // {{$id}}{{end}}

View File

@@ -20,7 +20,11 @@ import * as _noms from '@attic/noms';
_noms.registerPackage(pkg);
}
// enum.tmpl
export type Handedness =
0 | // right
1 | // left
2; // switch
export interface EnumStruct extends _noms.Struct {
hand: Handedness; // readonly

View File

@@ -28,4 +28,8 @@ export interface S extends _noms.Struct {
b: boolean; // readonly
setB(value: boolean): S;
}
// enum.tmpl
export type E =
0 | // e1
1 | // e2
2; // e3

View File

@@ -22,7 +22,10 @@ import * as _noms from '@attic/noms';
_noms.registerPackage(pkg);
}
// enum.tmpl
export type LocalE =
0 | // LocalE1
1; // Ignored
export interface ImportUser extends _noms.Struct {
importedStruct: D; // readonly

View File

@@ -28,4 +28,8 @@ export interface S extends _noms.Struct {
b: boolean; // readonly
setB(value: boolean): S;
}
// enum.tmpl
export type E =
0 | // e1
1 | // e2
2; // e3