@@ -14,22 +14,53 @@ See the License for the specific language governing permissions and
1414limitations under the License.
1515*/
1616
17- import { Annotated , Context } from "../../deps/@apexlang/core/model/mod.ts" ;
18- import { formatComment , typeName } from "../utils/mod.ts" ;
17+ import {
18+ Annotated ,
19+ Context ,
20+ Writer ,
21+ } from "../../deps/@apexlang/core/model/mod.ts" ;
22+ import { formatComment , snakeCase , typeName } from "../utils/mod.ts" ;
1923import { getImports , GoVisitor } from "./go_visitor.ts" ;
20- import { expandType , fieldName } from "./helpers.ts" ;
24+ import {
25+ expandType ,
26+ fieldName ,
27+ shouldWriteTypeInfo ,
28+ writeNamespaceEmbeddedStruct ,
29+ } from "./helpers.ts" ;
2130
2231interface UnionKey {
2332 value : string ;
2433}
2534
2635export class UnionVisitor extends GoVisitor {
36+ private writeTypeInfo : boolean ;
37+
38+ constructor ( writer : Writer , writeTypeInfo : boolean = false ) {
39+ super ( writer ) ;
40+ this . writeTypeInfo = writeTypeInfo ;
41+ }
42+
2743 public override visitUnion ( context : Context ) : void {
2844 const tick = "`" ;
2945 const { union } = context ;
3046 const imports = getImports ( context ) ;
47+
48+ const writeTypeInfo = shouldWriteTypeInfo ( context , this . writeTypeInfo ) ;
49+ if ( writeTypeInfo ) {
50+ writeNamespaceEmbeddedStruct ( context , this . writer ) ;
51+
52+ this . write (
53+ `const UNION_${
54+ snakeCase ( union . name ) . toUpperCase ( )
55+ } = "${ union . name } "\n\n`,
56+ ) ;
57+ }
58+
3159 this . write ( formatComment ( "// " , union . description ) ) ;
3260 this . write ( `type ${ union . name } struct {\n` ) ;
61+ if ( writeTypeInfo ) {
62+ this . write ( `ns\n` ) ;
63+ }
3364 union . members . forEach ( ( member ) => {
3465 let tname = typeName ( member . type ) ;
3566 member . annotation ( "unionKey" , ( a ) => {
@@ -50,5 +81,12 @@ export class UnionVisitor extends GoVisitor {
5081 this . write ( `"${ tick } \n` ) ;
5182 } ) ;
5283 this . write ( `}\n\n` ) ;
84+
85+ if ( writeTypeInfo ) {
86+ const receiver = union . name . substring ( 0 , 1 ) . toLowerCase ( ) ;
87+ this . write ( `func (${ receiver } *${ union . name } ) GetType() string {
88+ return UNION_${ snakeCase ( union . name ) . toUpperCase ( ) }
89+ }\n\n` ) ;
90+ }
5391 }
5492}
0 commit comments