1
1
import { ensureNodeDefinition , Node } from "../model/model" ;
2
- import { ReferenceByName } from "../model/naming" ;
3
2
import { Indexer } from "./indexing" ;
4
3
5
4
export const TO_JSON_SYMBOL = Symbol ( "toJSON" ) ;
@@ -14,46 +13,51 @@ export class JSONGenerator {
14
13
}
15
14
}
16
15
17
- Node . prototype [ TO_JSON_SYMBOL ] = function ( withIds ?: Indexer ) {
18
- const def = ensureNodeDefinition ( this ) ;
16
+ export function defaultToJSON ( node : Node , withIds ?: Indexer ) {
17
+ const def = ensureNodeDefinition ( node ) ;
19
18
const result = {
20
19
type : ( def . package ? def . package + "." : "" ) + def . name
21
20
} ;
22
21
23
22
if ( withIds ) {
24
- const id = withIds . getId ( this ) ;
25
- if ( id )
23
+ const id = withIds . getId ( node ) ;
24
+ if ( id ) {
26
25
result [ "id" ] = id ;
26
+ }
27
27
}
28
28
29
- const node = this as Node ;
30
- for ( const p in node ) {
31
- if ( p == 'parent' || p == 'parseTreeNode' ) {
32
- continue ;
33
- }
34
- const element = node [ p ] ;
35
- if ( element !== undefined && element !== null ) {
36
- const containment = node . containment ( p ) ;
37
- if ( containment ) {
38
- if ( containment . multiple ) {
39
- result [ p ] = element . map ( e => toJSON ( e ) ) ;
40
- } else {
41
- result [ p ] = toJSON ( element , withIds ) ;
29
+ for ( const p in node . nodeDefinition . features ) {
30
+ const feature = node . nodeDefinition . features [ p ] ;
31
+ if ( feature . child ) {
32
+ if ( feature . multiple ) {
33
+ const children = node . getChildren ( p ) ;
34
+ if ( children . length > 0 ) {
35
+ result [ p ] = children . map ( e => toJSON ( e , withIds ) ) ;
36
+ }
37
+ } else {
38
+ const child = node . getChild ( p ) ;
39
+ if ( child ) {
40
+ result [ p ] = toJSON ( child , withIds ) ;
42
41
}
43
42
}
44
- else if ( element instanceof ReferenceByName ) {
45
- const reference = element as ReferenceByName < any > ;
43
+ } else if ( feature . reference ) {
44
+ const reference = node . getReference ( p ) ;
45
+ if ( reference ) {
46
46
result [ p ] = {
47
- name : reference . name
48
- }
49
- if ( withIds ) {
50
- result [ p ] [ "referred" ] = reference . resolved ? withIds . getId ( reference . referred ) : undefined ;
47
+ name : reference . name ,
48
+ referred : reference . resolved ? withIds ?. getId ( reference . referred ) : undefined
51
49
}
52
50
}
53
- else if ( typeof node [ p ] !== "function" ) {
54
- result [ p ] = node [ p ] ;
51
+ } else {
52
+ const attributeValue = node . getAttributeValue ( p ) ;
53
+ if ( attributeValue !== undefined ) {
54
+ result [ p ] = attributeValue ;
55
55
}
56
56
}
57
57
}
58
58
return result ;
59
59
}
60
+
61
+ Node . prototype [ TO_JSON_SYMBOL ] = function ( withIds ?: Indexer ) {
62
+ return defaultToJSON ( this as Node , withIds ) ;
63
+ }
0 commit comments