@sap/cds-compiler 2.11.2 → 2.13.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +175 -2
  2. package/bin/.eslintrc.json +1 -2
  3. package/bin/cds_update_identifiers.js +10 -8
  4. package/bin/cdsc.js +23 -17
  5. package/bin/cdsse.js +2 -2
  6. package/bin/cdsv2m.js +3 -2
  7. package/doc/CHANGELOG_ARCHIVE.md +1 -1
  8. package/doc/CHANGELOG_BETA.md +25 -6
  9. package/doc/CHANGELOG_DEPRECATED.md +22 -6
  10. package/doc/NameResolution.md +21 -16
  11. package/lib/api/main.js +32 -79
  12. package/lib/api/options.js +3 -2
  13. package/lib/api/validate.js +2 -1
  14. package/lib/backends.js +16 -26
  15. package/lib/base/dictionaries.js +0 -8
  16. package/lib/base/error.js +26 -0
  17. package/lib/base/keywords.js +10 -19
  18. package/lib/base/location.js +9 -4
  19. package/lib/base/message-registry.js +75 -9
  20. package/lib/base/messages.js +31 -35
  21. package/lib/base/model.js +2 -62
  22. package/lib/base/optionProcessorHelper.js +246 -183
  23. package/lib/checks/.eslintrc.json +2 -0
  24. package/lib/checks/actionsFunctions.js +2 -1
  25. package/lib/checks/annotationsOData.js +1 -1
  26. package/lib/checks/cdsPersistence.js +2 -1
  27. package/lib/checks/emptyOrOnlyVirtual.js +2 -2
  28. package/lib/checks/enricher.js +17 -1
  29. package/lib/checks/foreignKeys.js +4 -4
  30. package/lib/checks/invalidTarget.js +3 -1
  31. package/lib/checks/managedInType.js +4 -4
  32. package/lib/checks/managedWithoutKeys.js +3 -1
  33. package/lib/checks/queryNoDbArtifacts.js +1 -3
  34. package/lib/checks/selectItems.js +4 -4
  35. package/lib/checks/sql-snippets.js +94 -0
  36. package/lib/checks/types.js +1 -1
  37. package/lib/checks/unknownMagic.js +1 -1
  38. package/lib/checks/validator.js +12 -7
  39. package/lib/compiler/assert-consistency.js +12 -8
  40. package/lib/compiler/base.js +0 -1
  41. package/lib/compiler/builtins.js +42 -21
  42. package/lib/compiler/checks.js +46 -12
  43. package/lib/compiler/cycle-detector.js +1 -1
  44. package/lib/compiler/define.js +1103 -0
  45. package/lib/compiler/extend.js +983 -0
  46. package/lib/compiler/finalize-parse-cdl.js +231 -0
  47. package/lib/compiler/index.js +46 -39
  48. package/lib/compiler/kick-start.js +190 -0
  49. package/lib/compiler/moduleLayers.js +4 -4
  50. package/lib/compiler/populate.js +1226 -0
  51. package/lib/compiler/propagator.js +113 -47
  52. package/lib/compiler/resolve.js +1433 -0
  53. package/lib/compiler/shared.js +100 -65
  54. package/lib/compiler/tweak-assocs.js +529 -0
  55. package/lib/compiler/utils.js +215 -33
  56. package/lib/edm/.eslintrc.json +5 -0
  57. package/lib/edm/annotations/genericTranslation.js +38 -25
  58. package/lib/edm/annotations/preprocessAnnotations.js +3 -3
  59. package/lib/edm/csn2edm.js +10 -9
  60. package/lib/edm/edm.js +19 -20
  61. package/lib/edm/edmPreprocessor.js +166 -95
  62. package/lib/edm/edmUtils.js +127 -34
  63. package/lib/gen/Dictionary.json +92 -43
  64. package/lib/gen/language.checksum +1 -1
  65. package/lib/gen/language.interp +11 -1
  66. package/lib/gen/language.tokens +86 -82
  67. package/lib/gen/languageLexer.interp +18 -1
  68. package/lib/gen/languageLexer.js +925 -847
  69. package/lib/gen/languageLexer.tokens +78 -74
  70. package/lib/gen/languageParser.js +5434 -4298
  71. package/lib/json/from-csn.js +59 -17
  72. package/lib/json/to-csn.js +189 -71
  73. package/lib/language/antlrParser.js +3 -3
  74. package/lib/language/docCommentParser.js +3 -3
  75. package/lib/language/errorStrategy.js +26 -8
  76. package/lib/language/genericAntlrParser.js +144 -53
  77. package/lib/language/language.g4 +424 -200
  78. package/lib/language/multiLineStringParser.js +536 -0
  79. package/lib/main.d.ts +550 -61
  80. package/lib/main.js +38 -11
  81. package/lib/model/api.js +3 -1
  82. package/lib/model/csnRefs.js +322 -198
  83. package/lib/model/csnUtils.js +226 -370
  84. package/lib/model/enrichCsn.js +124 -69
  85. package/lib/model/revealInternalProperties.js +29 -7
  86. package/lib/model/sortViews.js +10 -2
  87. package/lib/modelCompare/compare.js +17 -12
  88. package/lib/optionProcessor.js +8 -3
  89. package/lib/render/.eslintrc.json +1 -2
  90. package/lib/render/DuplicateChecker.js +1 -1
  91. package/lib/render/manageConstraints.js +36 -33
  92. package/lib/render/toCdl.js +174 -275
  93. package/lib/render/toHdbcds.js +203 -122
  94. package/lib/render/toRename.js +7 -10
  95. package/lib/render/toSql.js +161 -82
  96. package/lib/render/utils/common.js +22 -8
  97. package/lib/render/utils/sql.js +10 -7
  98. package/lib/render/utils/stringEscapes.js +111 -0
  99. package/lib/sql-identifier.js +1 -1
  100. package/lib/transform/.eslintrc.json +5 -0
  101. package/lib/transform/braceExpression.js +4 -2
  102. package/lib/transform/db/.eslintrc.json +2 -0
  103. package/lib/transform/db/applyTransformations.js +212 -0
  104. package/lib/transform/db/assertUnique.js +1 -1
  105. package/lib/transform/db/associations.js +187 -0
  106. package/lib/transform/db/cdsPersistence.js +150 -0
  107. package/lib/transform/db/constraints.js +61 -56
  108. package/lib/transform/db/expansion.js +50 -29
  109. package/lib/transform/db/flattening.js +556 -106
  110. package/lib/transform/db/groupByOrderBy.js +3 -1
  111. package/lib/transform/db/temporal.js +236 -0
  112. package/lib/transform/db/transformExists.js +103 -28
  113. package/lib/transform/db/views.js +92 -44
  114. package/lib/transform/draft/.eslintrc.json +38 -0
  115. package/lib/transform/{db/draft.js → draft/db.js} +9 -7
  116. package/lib/transform/draft/odata.js +227 -0
  117. package/lib/transform/forHanaNew.js +98 -783
  118. package/lib/transform/forOdataNew.js +22 -175
  119. package/lib/transform/localized.js +36 -32
  120. package/lib/transform/odata/generateForeignKeyElements.js +3 -3
  121. package/lib/transform/odata/referenceFlattener.js +95 -89
  122. package/lib/transform/odata/structureFlattener.js +1 -1
  123. package/lib/transform/odata/toFinalBaseType.js +86 -12
  124. package/lib/transform/odata/typesExposure.js +5 -5
  125. package/lib/transform/odata/utils.js +2 -2
  126. package/lib/transform/transformUtilsNew.js +47 -33
  127. package/lib/transform/translateAssocsToJoins.js +13 -30
  128. package/lib/transform/universalCsn/.eslintrc.json +36 -0
  129. package/lib/transform/universalCsn/coreComputed.js +170 -0
  130. package/lib/transform/universalCsn/universalCsnEnricher.js +715 -0
  131. package/lib/transform/universalCsn/utils.js +63 -0
  132. package/lib/utils/file.js +8 -3
  133. package/lib/utils/objectUtils.js +30 -0
  134. package/lib/utils/timetrace.js +8 -2
  135. package/package.json +1 -1
  136. package/share/messages/README.md +26 -0
  137. package/lib/compiler/definer.js +0 -2349
  138. package/lib/compiler/resolver.js +0 -2922
  139. package/lib/transform/db/helpers.js +0 -58
  140. package/lib/transform/universalCsnEnricher.js +0 -67
@@ -1,2349 +0,0 @@
1
- // Compiler phase "define": transform dictionary of AST-like CSNs into augmented CSN
2
-
3
- // AST-like CSN looks as follows:
4
- // { kind: 'source', env: <dictionary of artifact defs>, namespace: {}, ... }
5
- //
6
- // The property `artifacts` of a source contains the top-level definitions.
7
- // Definitions inside a context are not listed here (as opposed to
8
- // `definitions`, see below), but inside the property `artifacts` of that context.
9
-
10
- // The define phase (function 'define' below) enriches a dictionary of
11
- // (file names to) AST-like CSNs and restructure them a little bit, the result
12
- // is called "augmented CSN":
13
- // { sources: <dictionary of ASTs>, definitions: <dictionary of artifact defs> }
14
- //
15
- // The property `sources` is the input argument (dictionary of source ASTs).
16
- //
17
- // The property `definitions` is set by this compiler phase. It contains the
18
- // definitions of all main artifacts (i.e. not elements) from all sources, the
19
- // key is the absolute name of that artifact. These definitions are the same
20
- // objects as the definitions accessible via `sources` and `artifacts` of the
21
- // corresponding source/context.
22
- //
23
- // Because different sources could define artifacts with the same absolute
24
- // name, this compiler phase also put a property `messages` to the resulting
25
- // model, which is a vector of messages for the redefinitions. (Using the same
26
- // name for different definitions in one source is already recognized during
27
- // parsing.)
28
- //
29
- // You get the compact "official" CSN format by applying the function exported
30
- // by "../json/to-csn.js" to the augmented CSN.
31
-
32
- // Example 'file.cds':
33
- // namespace A;
34
- // context B {
35
- // type C { elem: String(4); }
36
- // }
37
- // Check the augmented CSN by compiling it with
38
- // cdsc --raw-output + file.cds
39
- //
40
- // ┌───────────────┐ ┌───────────────────────────────────────────┐
41
- // │ sources │ │ definitions │
42
- // └──┬────────────┘ └──┬────────────────────────────┬───────────┘
43
- // │ │ │
44
- // │ ['file.cds'] │ ['A.B'] │ ['A.B.C']
45
- // ↓ ↓ ↓
46
- // ┌───────────────┐ _parent ┌────────────────┐ _parent ┌──────────────┐
47
- // │ kind:'source' │←──────────┤ kind:'context' │←──────────┤ kind: 'type' │
48
- // │ artifacts: ───┼──────────→│ artifacts: ────┼──────────→│ ... │
49
- // └───────────────┘ ['B'] └────────────────┘ ['C'] └──────────────┘
50
- //
51
- // The _parent properties are not shown in the JSON - they are used for name
52
- // resolution, see file './resolver.js'.
53
-
54
- // An artifact definition looks as follows (example: context "A.B" above):
55
- // {
56
- // kind: 'context',
57
- // name: { id: 'B', absolute: 'A.B', location: { <for the id "B"> } },
58
- // artifacts: <for contexts, a dictionary of artifacts defined within>,
59
- // location: { <of the complete artifact definition> } },
60
- // _parent: <the parent artifact, here the source 'file.cds'>
61
- // }
62
- // The properties `name.absolute`, `name.component` and `_parent` are set
63
- // during this compiler phase.
64
-
65
- // The definition of an entity or a structured type would contain an `elements`
66
- // property instead of an `artifacts` property.
67
-
68
- // An element definition looks as follows (example: "elem" above):
69
- // {
70
- // kind: 'element',
71
- // name: { id: 'elem', component: 'elem', location: { <for the id "elem"> } }
72
- // type: { path: [ { id: 'String', location: ... } ] },
73
- // $typeArgs: [ { number: '4', location: ... } ]
74
- // location: { <of the complete element definition> } },
75
- // _parent: <the parent artifact, here the type "A.B.C">
76
- // }
77
- // References are resolved in the "resolve" phase of the compiler, see
78
- // './resolver.js'. We then get the properties `type.absolute` and `length`.
79
-
80
- // Sub phase 1 (addXYZ) - only for main artifats
81
- // - set _block links
82
- // - store definitions (including context extensions), NO duplicate check
83
- // - artifact name check
84
- // - Note: the only allow name resolving is resolveUncheckedPath(),
85
- // TODO: make sure that _no_ _artifact link is set
86
- // - POST: all user-written definitions are in model.definitions
87
-
88
- // Sub Phase 2 (initXYZ)
89
- // - set _parent, _main (later: _service?) links, and _block links of members
90
- // - add _subArtifacts dictionary and "namespace artifacts" for name resolution
91
- // - duplicate checks
92
- // - structure checks ?
93
- // - annotation assignments
94
- // - POST: resolvePath() can be called for artifact references (if complete model)
95
-
96
- // More sub phases...
97
-
98
- // The main difficulty is the correct behavior concerning duplicate definitions
99
- // - We need a unique object for the _subArtifacts dictionary.
100
- // - We must have a property at the artifact whether there are duplicates in order
101
- // to avoid consequential or repeated errors.
102
- // - But: The same artifact is added to multiple dictionaries.
103
- // - Solution part 1: $duplicates as property of the artifact or member
104
- // for `definitions`, `_artifacts`, member dictionaries, `vocabulary`
105
- // dictionary of the whole model, `$tableAliases` dictionary of queries.
106
- // - Solution part 2: array value in dictionary for duplicates in CDL `artifacts`
107
- // dictionary, `_combined` dictionary for query search, `$tableAliases`
108
- // of JOIN restrictions, `vocabulary` dictionary of a CDL input source.
109
-
110
- 'use strict';
111
-
112
- const { searchName, weakLocation } = require('../base/messages');
113
- const {
114
- isDeprecatedEnabled, isBetaEnabled,
115
- setProp, forEachGeneric, forEachInOrder,
116
- forEachDefinition,
117
- forEachMemberRecursivelyWithQuery,
118
- } = require('../base/model');
119
- const {
120
- dictAdd, dictAddArray, dictForEach, pushToDict,
121
- } = require('../base/dictionaries');
122
- const {
123
- dictLocation,
124
- } = require('../base/location');
125
- const { kindProperties, dictKinds } = require('./base');
126
- const {
127
- annotationVal,
128
- annotationIsFalse,
129
- annotateWith,
130
- linkToOrigin,
131
- setMemberParent,
132
- storeExtension,
133
- dependsOnSilent,
134
- augmentPath,
135
- splitIntoPath,
136
- } = require('./utils');
137
- const { compareLayer, layer } = require('./moduleLayers');
138
- const { initBuiltins, isInReservedNamespace } = require('./builtins');
139
- const setLink = setProp;
140
-
141
- /**
142
- * Export function of this file. Transform argument `sources` = dictionary of
143
- * AST-like CSNs into augmented CSN. If a vector is provided for argument
144
- * `messages` (usually the combined messages from `parse` for all sources), do
145
- * not throw an exception in case of an error, but push the corresponding error
146
- * object to that vector. If at least one AST does not exist due to a parse
147
- * error, set property `lintMode` of `options` to `true`. Then, the resolver
148
- * does not report errors for using directives pointing to non-existing
149
- * artifacts.
150
- *
151
- * @param {XSN.Model} model Model with `sources` property that contain AST-like CSNs.
152
- */
153
- function define( model ) {
154
- const { options } = model;
155
- // Get simplified "resolve" functionality and the message function:
156
- const {
157
- message, error, warning, info, messages,
158
- } = model.$messageFunctions;
159
- const {
160
- resolveUncheckedPath,
161
- resolvePath,
162
- resolveTypeArguments,
163
- defineAnnotations,
164
- attachAndEmitValidNames,
165
- } = model.$functions;
166
- Object.assign( model.$functions, {
167
- initArtifact,
168
- lateExtensions,
169
- projectionAncestor,
170
- hasTruthyProp,
171
- } );
172
- // During the definer, we can only resolve artifact references, i.e,
173
- // after a `.`, we only search in the `_subArtifacts` dictionary:
174
- model.$volatileFunctions.environment = function artifactsEnv( art ) {
175
- return art._subArtifacts || Object.create(null);
176
- };
177
-
178
- const extensionsDict = Object.create(null);
179
- let addTextsLanguageAssoc = false;
180
- return doDefine();
181
-
182
- /**
183
- * Main function of the definer.
184
- *
185
- * @returns {XSN.Model}
186
- */
187
- function doDefine() {
188
- if (options.deprecated &&
189
- messages.every( m => m.messageId !== 'api-deprecated-option' )) {
190
- warning( 'api-deprecated-option', {},
191
- { prop: 'deprecated', '#': (options.beta ? 'beta' : 'std') }, {
192
- // TODO: make the text scarier in future versions
193
- std: 'With option $(PROP), many newer features are disabled',
194
- // eslint-disable-next-line max-len
195
- beta: 'With option $(PROP), beta features and many other newer features are disabled',
196
- } );
197
- }
198
- model.definitions = Object.create(null);
199
- setProp( model, '_entities', [] ); // for entities with includes
200
- model.$entity = 0;
201
- model.$compositionTargets = Object.create(null);
202
- model.$lateExtensions = Object.create(null); // for generated artifacts
203
-
204
- initBuiltins( model );
205
- for (const name in model.sources)
206
- addSource( model.sources[name] );
207
- for (const name in model.sources)
208
- initNamespaceAndUsing( model.sources[name] );
209
- dictForEach( model.definitions, initArtifact );
210
- dictForEach( model.vocabularies, initVocabulary );
211
-
212
- mergeI18nBlocks( model );
213
-
214
- if (options.parseCdl) {
215
- initExtensionsWithoutApplying();
216
- // If no extensions shall be applied then we can skip further
217
- // artifact processing and return the model with an `extensions` property.
218
- return model;
219
- }
220
-
221
- applyExtensions();
222
-
223
- const commonLanguagesEntity // TODO: remove beta after a grace period
224
- = (options.addTextsLanguageAssoc || isBetaEnabled( options, 'addTextsLanguageAssoc' )) &&
225
- model.definitions['sap.common.Languages'];
226
- addTextsLanguageAssoc = !!(commonLanguagesEntity && commonLanguagesEntity.elements &&
227
- commonLanguagesEntity.elements.code);
228
- Object.keys( model.definitions ).forEach( processArtifact );
229
- lateExtensions( false );
230
- // Set _service link (sorted to set it on parent first). Could be set
231
- // directly, but beware a namespace becoming a service later.
232
- Object.keys( model.definitions ).sort().forEach( setAncestorsAndService );
233
- forEachGeneric( model, 'definitions', postProcessArtifact );
234
- return model;
235
- }
236
-
237
- // Phase 1: ----------------------------------------------------------------
238
-
239
- /**
240
- * Add definitions of the given source AST, both CDL and CSN
241
- *
242
- * @param {XSN.AST} src
243
- */
244
- function addSource( src ) {
245
- // handle sub model from parser
246
- if (!src.kind)
247
- src.kind = 'source';
248
-
249
- let namespace = src.namespace && src.namespace.path;
250
- let prefix = namespace ? `${ pathName( namespace ) }.` : '';
251
- if (isInReservedNamespace(prefix)) {
252
- error( 'reserved-namespace-cds', [ src.namespace.location, src.namespace ], {},
253
- // TODO: use $(NAME)
254
- 'The namespace "cds" is reserved for CDS builtins' );
255
- namespace = null;
256
- }
257
- if (src.$frontend !== 'json') { // CDL input
258
- // TODO: set _block to builtin
259
- if (src.artifacts)
260
- addPathPrefixes( src.artifacts, prefix ); // before addUsing
261
- else if (src.usings || src.namespace)
262
- src.artifacts = Object.create(null);
263
- if (src.usings)
264
- src.usings.forEach( u => addUsing( u, src ) );
265
- if (namespace)
266
- addNamespace( namespace, src );
267
- if (src.artifacts) // addArtifact needs usings for context extensions
268
- dictForEach( src.artifacts, a => addArtifact( a, src, prefix ) );
269
- }
270
- else if (src.definitions) { // CSN input
271
- prefix = '';
272
- dictForEach( src.definitions, v => addDefinition( v, src ) );
273
- }
274
- if (src.vocabularies) {
275
- if (!model.vocabularies)
276
- model.vocabularies = Object.create(null);
277
- dictForEach( src.vocabularies, v => addVocabulary( v, src, prefix ) );
278
- }
279
- if (src.extensions) { // requires using to be known!
280
- src.extensions.forEach( e => addExtension( e, src ) );
281
- }
282
- }
283
-
284
- function addDefinition( art, block ) {
285
- const { absolute } = art.name;
286
- // TODO: check reserved, see checkName()/checkLocalizedObjects() of checks.js
287
- if (absolute === 'cds' || isInReservedNamespace(absolute)) {
288
- error( 'reserved-namespace-cds', [ art.name.location, art ], {},
289
- // TODO: use $(NAME)
290
- 'The namespace "cds" is reserved for CDS builtins' );
291
- }
292
- else if (absolute === 'localized' || absolute.startsWith( 'localized.' )) {
293
- if (!art.query && art.kind !== 'context') { // context for recompilation (TODO: necessary?)
294
- error( 'reserved-namespace-localized', [ art.name.location, art ], {},
295
- 'The namespace "localized" is reserved for localization views' );
296
- }
297
- else if (block.$frontend !== 'json') {
298
- info( 'ignored-localized-definition', [ art.name.location, art ], {},
299
- 'This definition in the namespace "localized" is ignored' );
300
- }
301
- else if (!block.$withLocalized && !options.$recompile) { // block = src
302
- block.$withLocalized = true;
303
- info( 'recalculated-localized', [ art.name.location, null ], {},
304
- 'Input CSN contains localization view definitions which are re-calculated' );
305
- }
306
- art.$inferred = 'LOCALIZED-IGNORED';
307
- return false;
308
- }
309
- else {
310
- setLink( art, '_block', block );
311
- // dictAdd might set $duplicates to true
312
- dictAdd( model.definitions, absolute, art );
313
- return true;
314
- }
315
- return false;
316
- }
317
-
318
- // If 'A.B.C' is in 'artifacts', also add 'A' for name resolution
319
- function addPathPrefixes( artifacts, prefix ) {
320
- for (const name in artifacts) {
321
- const d = artifacts[name];
322
- const a = Array.isArray(d) ? d[0] : d;
323
- if (!a.name.absolute)
324
- a.name.absolute = prefix + name;
325
- const index = name.indexOf( '.' );
326
- if (index < 0)
327
- continue; // also for newly added (i.e. does not matter whether visited or not)
328
- const id = name.substring( 0, index );
329
- if (artifacts[id])
330
- continue;
331
- // TODO: enable optional locations
332
- const location = a.name.path && a.name.path[0].location || a.location;
333
- const absolute = prefix + id;
334
- artifacts[id] = {
335
- kind: 'using', // !, not namespace - we do not know artifact yet
336
- name: {
337
- id, absolute, location, $inferred: 'as',
338
- },
339
- // TODO: use global ref (in general - all uses of splitIntoPath)
340
- extern: { path: splitIntoPath( location, absolute ), location },
341
- location,
342
- $inferred: 'path-prefix',
343
- };
344
- }
345
- }
346
-
347
-
348
- /**
349
- * Add the names of a USING declaration to the top-level search environment
350
- * of the source, and set the absolute name referred by the USING
351
- * declaration.
352
- *
353
- * @param {XSN.Using} decl Node to be expanded and added to `src`
354
- * @param {XSN.AST} src
355
- */
356
- function addUsing( decl, src ) {
357
- if (decl.usings) {
358
- // e.g. `using {a,b} from 'file.cds'` -> recursive
359
- decl.usings.forEach( u => addUsing( u, src ) );
360
- return;
361
- }
362
- const { path } = decl.extern;
363
- if (path.broken || !path[0]) // syntax error
364
- return;
365
- if (!decl.name)
366
- decl.name = { ...path[path.length - 1], $inferred: 'as' };
367
- decl.name.absolute = pathName( path );
368
- const name = decl.name.id;
369
- // TODO: check name: no "."
370
- if (path[0].id === 'localized' || path[0].id.startsWith( 'localized.' )) {
371
- decl.$inferred = 'LOCALIZED-IGNORED';
372
- warning( 'using-localized-view', [ path.location, decl ], {},
373
- 'Localization views can\'t be referred to - ignored USING' );
374
- // actually not ignored anymore
375
- }
376
- const found = src.artifacts[name];
377
- if (found && found.$inferred === 'path-prefix' &&
378
- found.name.absolute === decl.name.absolute)
379
- src.artifacts[name] = decl;
380
- else
381
- dictAddArray( src.artifacts, name, decl );
382
- }
383
-
384
- function addNamespace( path, src ) {
385
- const absolute = pathName( path );
386
- if (path.broken) // parsing may have failed
387
- return;
388
- // create using for own namespace:
389
- const last = path[path.length - 1];
390
- const { id } = last;
391
- if (src.artifacts[id] || last.id.includes('.'))
392
- // not used as we have a definition/using with that name, or dotted last path id
393
- return;
394
- src.artifacts[id] = {
395
- kind: 'using',
396
- name: {
397
- id, absolute, location: last.location, $inferred: 'as',
398
- },
399
- extern: src.namespace,
400
- location: src.namespace.location,
401
- $inferred: 'namespace',
402
- };
403
- }
404
- function addArtifact( art, block, prefix ) {
405
- if (art.kind === 'using')
406
- return;
407
- art.name.absolute = prefix + pathName( art.name.path );
408
- addDefinition( art, block );
409
- if (art.artifacts) {
410
- const p = `${ art.name.absolute }.`;
411
- // path prefixes (usings) must be added before extensions in artifacts:
412
- addPathPrefixes( art.artifacts, p );
413
- dictForEach( art.artifacts, a => addArtifact( a, art, p ) );
414
- }
415
- if (art.extensions) { // requires using to be known!
416
- art.extensions.forEach( e => e.name && addExtension( e, art ) );
417
- }
418
- }
419
-
420
- function addExtension( ext, block ) {
421
- setLink( ext, '_block', block );
422
- const absolute = ext.name && resolveUncheckedPath( ext.name, 'extend', ext );
423
- if (!absolute) // broken path
424
- return;
425
- delete ext.name.path[0]._artifact; // might point to wrong JS object in phase 1
426
- ext.name.absolute = absolute; // definition might not be there yet, no _artifact link
427
- pushToDict( extensionsDict, absolute, ext );
428
- if (!ext.artifacts)
429
- return;
430
- // Directly add the artifacts of context and service extension:
431
- if (!model.$blocks)
432
- model.$blocks = Object.create( null );
433
- // Set block number for debugging (--raw-output):
434
- // eslint-disable-next-line no-multi-assign
435
- ext.name.select = model.$blocks[absolute] = (model.$blocks[absolute] || 0) + 1;
436
- const prefix = `${ absolute }.`;
437
- dictForEach( ext.artifacts, a => addArtifact( a, ext, prefix ) );
438
- }
439
-
440
- function addVocabulary( vocab, block, prefix ) {
441
- setLink( vocab, '_block', block );
442
- const { name } = vocab;
443
- if (!name.absolute)
444
- name.absolute = prefix + name.path.map( id => id.id ).join('.');
445
- dictAdd( model.vocabularies, name.absolute, vocab );
446
- }
447
-
448
- // Phase 2 ("init") --------------------------------------------------------
449
-
450
- function checkRedefinition( art ) {
451
- if (!art.$duplicates)
452
- return;
453
- if (art._main) {
454
- error( 'duplicate-definition', [ art.name.location, art ], {
455
- name: art.name.id,
456
- '#': kindProperties[art.kind].normalized || art.kind,
457
- } );
458
- }
459
- else {
460
- error( 'duplicate-definition', [ art.name.location, art ], {
461
- name: art.name.absolute,
462
- '#': (art.kind === 'annotation' ? 'annotation' : 'absolute' ),
463
- } );
464
- }
465
- }
466
-
467
- function initNamespaceAndUsing( src ) {
468
- if (src.namespace) {
469
- const decl = src.namespace;
470
- const { path } = decl;
471
- if (path.broken) // parsing may have failed
472
- return;
473
- const { id } = path[path.length - 1];
474
- const absolute = pathName( path );
475
- if (!model.definitions[absolute]) {
476
- // TODO: do we really need this namespace entry - try without (msg change)
477
- const location = path.location || decl.location;
478
- // TODO: make it possible to have no location
479
- const ns = { kind: 'namespace', name: { absolute, location }, location };
480
- model.definitions[absolute] = ns;
481
- initParentLink( ns, model.definitions );
482
- }
483
- const builtin = model.$builtins[id];
484
- if (builtin && !builtin.internal &&
485
- src.artifacts[id] && src.artifacts[id].extern === decl) {
486
- warning( 'ref-shadowed-builtin', [ decl.location, null ], // no home artifact
487
- { id, art: absolute, code: `using ${ builtin.name.absolute };` },
488
- '$(ID) now refers to $(ART) - consider $(CODE)' );
489
- }
490
- // setLink( decl, '_artifact', model.definitions[absolute] ); // TODO: necessary?
491
- }
492
- if (!src.usings)
493
- return;
494
- for (const name in src.artifacts) {
495
- const entry = src.artifacts[name];
496
- if (!Array.isArray(entry)) // no local name duplicate
497
- continue;
498
- for (const decl of entry) {
499
- if (!decl.$duplicates) { // do not have two duplicate messages
500
- error( 'duplicate-using', [ decl.name.location, null ], { name }, // TODO: semantic
501
- 'Duplicate definition of top-level name $(NAME)' );
502
- }
503
- }
504
- }
505
- }
506
-
507
- function initArtifact( art, reInit = false ) {
508
- if (!reInit)
509
- initParentLink( art, model.definitions );
510
- const block = art._block;
511
- checkRedefinition( art );
512
- defineAnnotations( art, art, block );
513
- initMembers( art, art, block );
514
- initDollarSelf( art ); // $self
515
- if (art.params)
516
- initParams( art ); // $parameters
517
- if (art.includes && !(art.name.absolute in extensionsDict)) // TODO: in next phase?
518
- extensionsDict[art.name.absolute] = []; // structure with includes must be "extended"
519
-
520
- if (!art.query)
521
- return;
522
- art.$queries = [];
523
- setLink( art, '_from', [] ); // for sequence of resolve steps
524
- if (!setLink( art, '_leadingQuery', initQueryExpression( art.query, art ) ) )
525
- return; // null or undefined in case of parse error
526
- setProp( art._leadingQuery, '_$next', art );
527
- // the following we be removed soon if we have:
528
- // view elements as proxies to elements of leading query
529
- if (art.elements) { // specified element via compilation of client-style CSN
530
- setProp( art, 'elements$', art.elements );
531
- delete art.elements;
532
- }
533
- }
534
-
535
- function initVocabulary( art ) {
536
- initParentLink( art, model.vocabularies );
537
- checkRedefinition( art );
538
- const block = art._block;
539
- defineAnnotations( art, art, block );
540
- initMembers( art, art, block );
541
- }
542
-
543
- function initParentLink( art, definitions ) {
544
- setLink( art, '_parent', null );
545
- const { absolute } = art.name;
546
- const dot = absolute.lastIndexOf('.');
547
- if (dot < 0)
548
- return;
549
- art.name.id = absolute.substring( dot + 1 ); // XSN TODO: remove name.id for artifacts
550
- const prefix = absolute.substring( 0, dot );
551
- let parent = definitions[prefix];
552
- if (!parent) {
553
- const { location } = art.name; // TODO: make it possible to have no location
554
- parent = { kind: 'namespace', name: { absolute: prefix, location }, location };
555
- definitions[prefix] = parent;
556
- initParentLink( parent, definitions );
557
- }
558
- if (art.kind !== 'namespace' &&
559
- isDeprecatedEnabled( options, 'generatedEntityNameWithUnderscore' )) {
560
- let p = parent;
561
- while (p && kindProperties[p.kind].artifacts)
562
- p = p._parent;
563
- if (p) {
564
- error( 'subartifacts-not-supported', [ art.name.location, art ],
565
- { art: p, prop: 'deprecated.generatedEntityNameWithUnderscore' },
566
- // eslint-disable-next-line max-len
567
- 'With the option $(PROP), no sub artifact can be defined for a non-context/service $(ART)' );
568
- }
569
- }
570
- setLink( art, '_parent', parent );
571
- if (!parent._subArtifacts)
572
- setLink( parent, '_subArtifacts', Object.create(null) );
573
- if (art.$duplicates !== true) // no redef or "first def"
574
- parent._subArtifacts[absolute.substring( dot + 1 )] = art; // not dictAdd()
575
- }
576
-
577
- // From here til EOF, reexamine code ---------------------------------------
578
-
579
- function initDollarSelf( art ) {
580
- const selfname = '$self';
581
- // TODO: use setMemberParent() ?
582
- const self = {
583
- name: { id: selfname, alias: selfname, absolute: art.name.absolute },
584
- kind: '$self',
585
- location: art.location,
586
- };
587
- setProp( self, '_parent', art );
588
- setProp( self, '_main', art ); // used on main artifact
589
- setProp( self, '_origin', art );
590
- art.$tableAliases = Object.create(null);
591
- art.$tableAliases[selfname] = self;
592
- setProp( art, '_$next', model.$magicVariables );
593
- }
594
-
595
- function initParams( art ) {
596
- // TODO: use setMemberParent() ?
597
- const parameters = {
598
- name: { id: '$parameters', param: '$parameters', absolute: art.name.absolute },
599
- kind: '$parameters',
600
- location: art.location,
601
- };
602
- setProp( parameters, '_parent', art );
603
- setProp( parameters, '_main', art );
604
- // Search for :const after :param. If there will be a possibility in the
605
- // future that we can extend <query>.columns, we must be sure to use
606
- // _block of that new column after :param (or just allow $parameters there).
607
- setProp( parameters, '_block', art._block );
608
- if (art.params) {
609
- parameters.elements = art.params;
610
- parameters.$tableAliases = art.params; // TODO: find better name - $lexical?
611
- }
612
- art.$tableAliases.$parameters = parameters;
613
- }
614
-
615
- function initSubQuery( query ) {
616
- if (query.on)
617
- initExprForQuery( query.on, query );
618
- // TODO: MIXIN with name = ...subquery (not yet supported anyway)
619
- initSelectItems( query, query.columns );
620
- if (query.where)
621
- initExprForQuery( query.where, query );
622
- if (query.having)
623
- initExprForQuery( query.having, query );
624
- initMembers( query, query, query._block );
625
- }
626
-
627
- function initSelectItems( parent, columns ) {
628
- // TODO: forbid expand/inline with :param, global:true, in ref-where, outside queries (CSN), ...
629
- let wildcard = null;
630
- for (const col of columns || parent.expand || parent.inline || []) {
631
- if (!col) // parse error
632
- continue;
633
- if (!columns) {
634
- if (parent.value)
635
- setProp( col, '_pathHead', parent ); // also set for '*' in expand/inline
636
- else if (parent._pathHead)
637
- setProp( col, '_pathHead', parent._pathHead );
638
- }
639
- if (col.val === '*') {
640
- if (!wildcard) {
641
- wildcard = col;
642
- }
643
- else {
644
- // a late syntax error (this code also runs with parse-cdl), i.e.
645
- // no semantic loc (wouldn't be available for expand/inline anyway)
646
- error( 'syntax-duplicate-clause', [ col.location, null ],
647
- { prop: '*', line: wildcard.location.line, col: wildcard.location.col },
648
- 'You have provided a $(PROP) already at line $(LINE), column $(COL)' );
649
- // TODO: extra text variants for expand/inline? - probably not
650
- col.val = null; // do not consider it for expandWildcard()
651
- }
652
- }
653
- else if (col.value || col.expand) {
654
- setProp( col, '_block', parent._block );
655
- defineAnnotations( col, col, parent._block ); // TODO: complain with inline
656
- // TODO: allow sub queries? at least in top-level expand without parallel ref
657
- if (columns)
658
- initExprForQuery( col.value, parent );
659
- initSelectItems( col );
660
- }
661
- }
662
- }
663
-
664
- function initExprForQuery( expr, query ) {
665
- if (Array.isArray(expr)) { // TODO: old-style $parens ?
666
- expr.forEach( e => initExprForQuery( e, query ) );
667
- }
668
- else if (!expr) {
669
- return;
670
- }
671
- else if (expr.query) {
672
- initQueryExpression( expr.query, query );
673
- }
674
- else if (expr.args) {
675
- const args = Array.isArray(expr.args) ? expr.args : Object.values( expr.args );
676
- args.forEach( e => initExprForQuery( e, query ) );
677
- }
678
- else if (expr.path && expr.$expected === 'exists') {
679
- expr.$expected = 'approved-exists';
680
- approveExistsInChildren(expr);
681
- }
682
- }
683
-
684
- /**
685
- * If we have a valid top-level exists, exists in filters of sub-expressions can be translated,
686
- * since we will have a top-level subquery after exists-processing in the forHanaNew.
687
- *
688
- * Recursively drill down into:
689
- * - the .path
690
- * - the .args
691
- * - the .where.args
692
- *
693
- * Any $expected === 'exists' encountered along the way are turned into 'approved-exists'
694
- *
695
- * working: exists toE[exists toE] -> select from E where exists toE
696
- * not working: toE[exists toE] -> we don't support subqueries in filters
697
- *
698
- * @param {object} exprOrPathElement starts w/ an expr but then subelem from .path or .where.args
699
- */
700
- function approveExistsInChildren(exprOrPathElement) {
701
- if (exprOrPathElement.$expected === 'exists')
702
- exprOrPathElement.$expected = 'approved-exists';
703
- // Drill down
704
- if (exprOrPathElement.args)
705
- exprOrPathElement.args.forEach(elem => approveExistsInChildren(elem));
706
- else if (exprOrPathElement.where && exprOrPathElement.where.args)
707
- exprOrPathElement.where.args.forEach(elem => approveExistsInChildren(elem));
708
- else if (exprOrPathElement.path)
709
- exprOrPathElement.path.forEach(elem => approveExistsInChildren(elem));
710
- }
711
-
712
- // table is table expression in FROM, becomes an alias
713
- function initTableExpression( table, query, joinParents ) {
714
- if (!table) // parse error
715
- return;
716
- if (table.path) { // path in FROM
717
- if (!table.path.length || table.path.broken)
718
- // parse error (e.g. final ',' in FROM), projection on <eof>
719
- return;
720
- if (!table.name) {
721
- const last = table.path[table.path.length - 1];
722
- const dot = last.id.lastIndexOf('.');
723
- const id = (dot < 0) ? last.id : last.id.substring( dot + 1 );
724
- // TODO: if we have too much time, we can calculate the real location with '.'
725
- table.name = { $inferred: 'as', id, location: last.location };
726
- }
727
- addAsAlias();
728
- // _origin is set when we resolve the ref
729
- if (query._parent.kind !== 'select')
730
- query._main._from.push( table ); // store tabref if outside "real" subquery
731
- }
732
- else if (table.query) {
733
- if (!table.name || !table.name.id) {
734
- error( 'query-req-alias', [ table.location, query ], {}, // TODO: not subquery.location ?
735
- 'Table alias is required for this subquery' );
736
- return;
737
- }
738
- addAsAlias();
739
- setProp( table, '_effectiveType', table.query ); // TODO: remove!
740
- // Store _origin to leading query of table.query for name resolution
741
- setProp( table, '_origin', initQueryExpression( table.query, table ) );
742
- }
743
- else if (table.join) {
744
- if (table.on) {
745
- setProp( table, '_$next', query ); // or query._$next?
746
- setProp( table, '_block', query._block );
747
- table.kind = '$join';
748
- table.name = { location: query.location }; // param comes later
749
- table.$tableAliases = Object.create( null ); // table aliases and mixin definitions
750
- joinParents = [ ...joinParents, table ];
751
- }
752
- if (table.args) {
753
- table.args.forEach( (tab, index) => {
754
- // set for A2J such that for every table alias `ta`:
755
- // ta === (ta._joinParent
756
- // ? ta._joinParent.args[ta.$joinArgsIndex] // in JOIN
757
- // : ta._parent.from ) // directly in FROM
758
- // Note for --raw-output: _joinParent pointing to CROSS JOIN node has not name
759
- if (!tab) // parse error; time for #6241
760
- return; // (parser method to only add non-null to array)
761
- setProp( tab, '_joinParent', table );
762
- tab.$joinArgsIndex = index;
763
- initTableExpression( tab, query, joinParents );
764
- } );
765
- }
766
- if (table.on) { // after processing args to get the $tableAliases
767
- setMemberParent( table, query.name.select, query ); // sets _parent,_main
768
- initSubQuery( table ); // init sub queries in ON
769
- const aliases = Object.keys( table.$tableAliases || {} );
770
- // Use first tabalias name on the right side of the join to name the
771
- // (internal) query, should only be relevant for --raw-output, not for
772
- // user messages or references - TODO: correct if join on left?
773
- table.name.param = aliases[1] || aliases[0] || '<unknown>';
774
- setProp( table, '_$next', query._$next );
775
- // TODO: probably set this to query if we switch to name restriction in JOIN
776
- }
777
- }
778
- return;
779
-
780
- function addAsAlias() {
781
- table.kind = '$tableAlias';
782
- setMemberParent( table, table.name.id, query );
783
- setProp( table, '_block', query._block );
784
- dictAdd( query.$tableAliases, table.name.id, table, ( name, loc ) => {
785
- error( 'duplicate-definition', [ loc, table ], { name, '#': 'alias' } );
786
- } );
787
- // also add to JOIN nodes for name restrictions:
788
- for (const p of joinParents) {
789
- // for JOIN alias restriction, we cannot use $duplicates, as it is
790
- // already used for duplicate aliases of queries:
791
- dictAddArray( p.$tableAliases, table.name.id, table );
792
- }
793
- if (table.name.id[0] === '$') {
794
- warning( 'syntax-dollar-ident', [ table.name.location, table ], {
795
- '#': (table.name.$inferred ? '$tableImplicit' : '$tableAlias'),
796
- name: '$',
797
- keyword: 'as',
798
- } );
799
- }
800
- }
801
- }
802
-
803
- // art is:
804
- // - entity for top-level queries (including UNION args)
805
- // - $tableAlias for sub query in FROM
806
- // - $query for real sub query (in columns, WHERE, ...)
807
- function initQueryExpression( query, art ) {
808
- if (!query) // parse error
809
- return query;
810
- if (query.from) { // select
811
- initQuery();
812
- initTableExpression( query.from, query, [] );
813
- if (query.mixin)
814
- addMixin();
815
- if (!query.$tableAliases.$self) { // same as $projection
816
- const self = {
817
- name: { alias: '$self', query: query.name.select, absolute: art.name.absolute },
818
- kind: '$self',
819
- location: query.location,
820
- };
821
- setProp( self, '_origin', query );
822
- setProp( self, '_parent', query );
823
- setProp( self, '_main', query._main );
824
- setProp( self, '_effectiveType', query ); // TODO: remove
825
- query.$tableAliases.$self = self;
826
- query.$tableAliases.$projection = self;
827
- }
828
- initSubQuery( query ); // check for SELECT clauses after from / mixin
829
- }
830
- else if (query.args) { // UNION, INTERSECT, ..., query in parens
831
- const leading = initQueryExpression( query.args[0], art );
832
- for (const q of query.args.slice(1))
833
- initQueryExpression( q, art );
834
- setProp( query, '_leadingQuery', leading );
835
- if (leading && query.orderBy) {
836
- if (leading.$orderBy)
837
- leading.$orderBy.push( ...query.orderBy );
838
- else
839
- leading.$orderBy = [ ...query.orderBy ];
840
- }
841
- // ORDER BY to be evaluated in leading query (LIMIT is literal)
842
- }
843
- else { // with parse error (`select from <EOF>`, `select from E { *, ( select }`)
844
- return undefined;
845
- }
846
- return query._leadingQuery || query;
847
-
848
- function initQuery() {
849
- const main = art._main || art;
850
- setProp( query, '_$next',
851
- // if art is $tableAlias, set to embedding query
852
- (!art._main || art.kind === 'select' || art.kind === '$join')
853
- ? art : art._parent ); // TODO: check with name resolution change
854
- setProp( query, '_block', art._block );
855
- query.kind = 'select';
856
- query.name = { location: query.location };
857
- setMemberParent( query, main.$queries.length + 1, main );
858
- // console.log(JSON.stringify(query.name))
859
- // if (query.name.query === 1 && query.name.absolute === 'S') throw Error();
860
- main.$queries.push( query );
861
- setProp( query, '_parent', art ); // _parent should point to alias/main/query
862
- query.$tableAliases = Object.create( null ); // table aliases and mixin definitions
863
- dependsOnSilent( main, query );
864
- }
865
-
866
- function addMixin() {
867
- // TODO: re-check if mixins have already duplicates
868
- for (const name in query.mixin) {
869
- const mixin = query.mixin[name];
870
- if (!(mixin.$duplicates)) {
871
- setMemberParent( mixin, name, query );
872
- mixin.name.alias = mixin.name.id;
873
- setProp( mixin, '_block', art._block );
874
- // TODO: do some initMembers() ? If people had annotation
875
- // assignments on the mixin... (also for future mixin definitions
876
- // with generated values)
877
- dictAdd( query.$tableAliases, name, query.mixin[name], ( dupName, loc ) => {
878
- error( 'duplicate-definition', [ loc, query ], { name: dupName, '#': 'alias' } );
879
- } );
880
- if (mixin.name.id[0] === '$') {
881
- warning( 'syntax-dollar-ident', [ mixin.name.location, mixin ],
882
- { '#': 'mixin', name: '$' } );
883
- }
884
- }
885
- }
886
- }
887
- }
888
-
889
- function isDirectComposition( art ) {
890
- const type = art.type && art.type.path;
891
- return type && type[0] && type[0].id === 'cds.Composition';
892
- }
893
-
894
- // Return whether the `target` is actually a `targetAspect`
895
- function targetIsTargetAspect( elem ) {
896
- const { target } = elem;
897
- if (target.elements) {
898
- // TODO: error if CSN has both target.elements and targetAspect.elements -> delete target
899
- return true;
900
- }
901
- if (elem.targetAspect || options.parseCdl || !isDirectComposition( elem ))
902
- return false;
903
- const name = resolveUncheckedPath( target, 'compositionTarget', elem );
904
- const aspect = name && model.definitions[name];
905
- return aspect && (aspect.kind === 'aspect' || aspect.kind === 'type'); // type is sloppy
906
- }
907
-
908
- /**
909
- * Set property `_parent` for all elements in `parent` to `parent` and do so
910
- * recursively for all sub elements. Also set the property
911
- * `name.component` of the element with the help of argument `prefix`
912
- * (which is basically the component name of the `parent` element plus a dot).
913
- */
914
- function initMembers( construct, parent, block, initExtensions = false ) {
915
- // TODO: split extend from init
916
- const isQueryExtension = kindProperties[construct.kind].isExtension &&
917
- (parent._main || parent).query;
918
- let obj = construct;
919
- if (obj.items) {
920
- obj = obj.items;
921
- setProp( obj, '_outer', construct );
922
- setProp( obj, '_block', block );
923
- }
924
- if (obj.target && targetIsTargetAspect( obj )) {
925
- obj.targetAspect = obj.target;
926
- delete obj.target;
927
- }
928
- if (obj.targetAspect) {
929
- if (obj.foreignKeys) {
930
- error( 'unexpected-keys-for-composition', [ dictLocation( obj.foreignKeys ), construct ],
931
- {},
932
- 'A managed aspect composition can\'t have a foreign keys specification' );
933
- delete obj.foreignKeys; // continuation semantics: not specified
934
- }
935
- if (obj.on && !obj.target) {
936
- error( 'unexpected-on-for-composition', [ dictLocation( obj.foreignKeys ), construct ],
937
- {},
938
- 'A managed aspect composition can\'t have a specified ON condition' );
939
- delete obj.on; // continuation semantics: not specified
940
- }
941
- if (obj.targetAspect.elements) {
942
- obj = obj.targetAspect;
943
- setProp( obj, '_outer', construct );
944
- }
945
- }
946
- if (obj !== parent && obj.elements && parent.enum) {
947
- // in extensions, extended enums are represented as elements
948
- for (const n in obj.elements) {
949
- const e = obj.elements[n];
950
- if (e.kind === 'element')
951
- e.kind = 'enum';
952
- }
953
- // obj = Object.assign( { enum: obj.elements}, obj );
954
- // delete obj.elements; // No extra syntax for EXTEND enum
955
- forEachGeneric( { enum: obj.elements }, 'enum', init );
956
- }
957
- else {
958
- if (checkDefinitions( construct, parent, 'elements', obj.elements || false ))
959
- forEachInOrder( obj, 'elements', init );
960
- if (checkDefinitions( construct, parent, 'enum', obj.enum || false ))
961
- forEachGeneric( obj, 'enum', init );
962
- }
963
- if (obj.foreignKeys) // cannot be extended or annotated - TODO: check anyway?
964
- forEachInOrder( obj, 'foreignKeys', init );
965
- if (checkDefinitions( construct, parent, 'actions' ))
966
- forEachGeneric( construct, 'actions', init );
967
- if (checkDefinitions( construct, parent, 'params' ))
968
- forEachInOrder( construct, 'params', init );
969
- const { returns } = construct;
970
- if (returns) {
971
- returns.kind = (kindProperties[construct.kind].isExtension) ? construct.kind : 'param';
972
- init( returns, '' ); // '' is special name for returns parameter
973
- }
974
- return;
975
-
976
- function init( elem, name, prop ) {
977
- if (!elem.kind) // wrong CSN input
978
- elem.kind = dictKinds[prop];
979
- if (!elem.name) {
980
- const ref = elem.targetElement || elem.kind === 'element' && elem.value;
981
- if (ref && ref.path) {
982
- elem.name = Object.assign( { $inferred: 'as' },
983
- ref.path[ref.path.length - 1] );
984
- }
985
- else { // if JSON parser misses to set name
986
- elem.name = { id: name, location: elem.location };
987
- }
988
- }
989
- // if (!kindProperties[ elem.kind ]) console.log(elem.kind,elem.name)
990
- if (kindProperties[elem.kind].isExtension && !initExtensions) {
991
- storeExtension( elem, name, prop, parent, block );
992
- return;
993
- }
994
- if (isQueryExtension && elem.kind === 'element') {
995
- error( 'extend-query', [ elem.location, construct ], // TODO: searchName ?
996
- { art: parent._main || parent },
997
- 'Query entity $(ART) can only be extended with actions' );
998
- return;
999
- }
1000
-
1001
- const bl = elem._block || block;
1002
- setProp( elem, '_block', bl );
1003
- setMemberParent( elem, name, parent, construct !== parent && prop );
1004
- // console.log(message( null, elem.location, elem, {}, 'Info', 'INIT').toString())
1005
- checkRedefinition( elem );
1006
- defineAnnotations( elem, elem, bl );
1007
- initMembers( elem, elem, bl, initExtensions );
1008
-
1009
- // for a correct home path, setMemberParent needed to be called
1010
-
1011
- if (elem.value && elem.kind === 'element' ) {
1012
- // For enums in extensions, `elem.kind` is only changed to `enum` for non-parseCdl
1013
- // mode *and* if the referenced artifact is found.
1014
- // This means that for non-applicable extensions and parseCdl mode, this check
1015
- // is not used.
1016
- //
1017
- // `parent` is the extended entity/type/enum/... and *not* the "extend: ..."
1018
- // itself (which is `construct`).
1019
- if ( ![ 'select', 'extend' ].includes(parent.kind) ) {
1020
- error( 'unexpected-val', [ elem.value.location, elem ],
1021
- { '#': construct.kind },
1022
- {
1023
- std: 'Elements can\'t have a value',
1024
- entity: 'Entity elements can\'t have a value',
1025
- type: 'Type elements can\'t have a value',
1026
- extend: 'Cannot extend type/entity elements with values',
1027
- });
1028
- return;
1029
- }
1030
- }
1031
-
1032
- if (parent.enum && elem.type) {
1033
- // already rejected by from-csn, can only happen in extensions
1034
- error( 'unexpected-type', [ elem.type.location, elem ], {},
1035
- 'Enum values can\'t have a custom type' );
1036
- }
1037
- }
1038
- }
1039
-
1040
- function checkDefinitions( construct, parent, prop, dict = construct[prop] ) {
1041
- // TODO: do differently, see also annotateMembers() in resolver
1042
- // To have been checked by parsers:
1043
- // - artifacts (CDL-only anyway) only inside [extend] context|service
1044
- if (!dict)
1045
- return false;
1046
- const names = Object.getOwnPropertyNames( dict );
1047
- if (!names.length)
1048
- return false;
1049
- const feature = kindProperties[parent.kind][prop];
1050
- if (feature &&
1051
- (feature === true || construct.kind !== 'extend' || feature( prop, parent )))
1052
- return true;
1053
- const location = dictLocation( names.map( name => dict[name] ) );
1054
- if (prop === 'actions') {
1055
- error( 'unexpected-actions', [ location, construct ], {},
1056
- 'Actions and functions only exist top-level and for entities' );
1057
- }
1058
- else if (parent.kind === 'action' || parent.kind === 'function') {
1059
- error( 'extend-action', [ construct.location, construct ], {},
1060
- 'Actions and functions can\'t be extended, only annotated' );
1061
- }
1062
- else if (prop === 'params') {
1063
- if (!feature) {
1064
- // Note: This error can't be triggered at the moment. But as we likely want to
1065
- // allow extensions with params in the future, we keep the code.
1066
- error( 'unexpected-params', [ location, construct ], {},
1067
- 'Parameters only exist for entities, actions or functions' );
1068
- }
1069
- else {
1070
- // remark: we could allow this
1071
- error( 'extend-with-params', [ location, construct ], {},
1072
- 'Extending artifacts with parameters is not supported' );
1073
- }
1074
- }
1075
- else if (feature) { // allowed in principle, but not with extend
1076
- error( 'extend-type', [ location, construct ], {},
1077
- 'Only structures or enum types can be extended with elements/enums' );
1078
- }
1079
- else if (prop === 'elements') {
1080
- error( 'unexpected-elements', [ location, construct ], {},
1081
- 'Elements only exist in entities, types or typed constructs' );
1082
- }
1083
- else { // if (prop === 'enum') {
1084
- error( 'unexpected-enum', [ location, construct ], {},
1085
- 'Enum symbols can only be defined for types or typed constructs' );
1086
- }
1087
- return construct === parent;
1088
- }
1089
-
1090
- /**
1091
- * Set projection ancestors, and _service link for artifact with absolute name 'name':
1092
- * - not set: internal artifact
1093
- * - null: not within service
1094
- * - service: the artifact of the embedding service
1095
- * This function must be called ordered: parent first
1096
- *
1097
- * @param {string} name Artifact name
1098
- */
1099
- function setAncestorsAndService( name ) {
1100
- const art = model.definitions[name];
1101
- if (!('_parent' in art))
1102
- return; // nothing to do for builtins and redefinitions
1103
- if (art._from && !('_ancestors' in art))
1104
- setProjectionAncestors( art );
1105
-
1106
- let parent = art._parent;
1107
- if (parent === model.definitions.localized)
1108
- parent = model.definitions[name.substring( 'localized.'.length )];
1109
- const service = parent && (parent._service || parent.kind === 'service' && parent);
1110
- setProp( art, '_service', service );
1111
- if (!parent || !service)
1112
- return;
1113
- // To be removed when nested services are allowed
1114
- if (!isBetaEnabled(options, 'nestedServices') && art.kind === 'service') {
1115
- while (parent.kind !== 'service')
1116
- parent = parent._parent;
1117
- message( 'service-nested-service', [ art.name.location, art ], { art: parent },
1118
- 'A service can\'t be nested within a service $(ART)' );
1119
- }
1120
- else if (art.kind === 'context') {
1121
- while (parent.kind !== 'service')
1122
- parent = parent._parent;
1123
- // TODO: remove this error
1124
- message( 'service-nested-context', [ art.name.location, art ], { art: parent },
1125
- 'A context can\'t be nested within a service $(ART)' );
1126
- }
1127
- }
1128
-
1129
- function setProjectionAncestors( art ) {
1130
- // Must be run after processLocalizedData() as we could have a projection
1131
- // on a generated entity.
1132
-
1133
- // TODO: do not do implicit redirection across services, i.e. Service2.E is
1134
- // no redirection target for E if Service2.E = projection on Service1.E and
1135
- // Service1.E = projection on E
1136
- const chain = [];
1137
- const autoexposed = annotationVal( art['@cds.autoexposed'] );
1138
- const preferredRedirectionTarget = annotationVal( art['@cds.redirection.target'] );
1139
- // no need to set preferredRedirectionTarget in the while loop as we would
1140
- // use the projection having @cds.redirection.target anyhow instead of
1141
- // `art` anyway (if we do the no-x-service-implicit-redirection TODO above)
1142
- while (art && !('_ancestors' in art) &&
1143
- art._from && art._from.length === 1 &&
1144
- (preferredRedirectionTarget || !annotationIsFalse( art['@cds.redirection.target'] ) ) &&
1145
- art.query.op && art.query.op.val === 'SELECT') {
1146
- chain.push( art );
1147
- setProp( art, '_ancestors', null ); // avoid infloop with cyclic from
1148
- const name = resolveUncheckedPath( art._from[0], 'include', art ); // TODO: 'include'?
1149
- art = name && projectionAncestor( model.definitions[name], art.params );
1150
- if (autoexposed)
1151
- break; // only direct projection for auto-exposed
1152
- }
1153
- let ancestors = art && (!autoexposed && art._ancestors || []);
1154
- for (const a of chain.reverse()) {
1155
- ancestors = (ancestors ? [ ...ancestors, art ] : []);
1156
- setProp( a, '_ancestors', ancestors );
1157
- art = a;
1158
- }
1159
- }
1160
-
1161
- // Return argument `source` if entity `source` has parameters like `params`
1162
- // - same parameters, although `params` can contain a new optional one (with DEFAULT)
1163
- // - a parameter in `params` can be optional which is not in `source.params`, but not vice versa
1164
- // - exactly the same types (type argument do not matter)
1165
- function projectionAncestor( source, params ) {
1166
- if (!source)
1167
- return source;
1168
- if (!params) // proj has no params => ok if source has no params
1169
- return !source.params && source;
1170
- const sourceParams = source.params || Object.create(null);
1171
- for (const n in sourceParams) {
1172
- if (!(n in params)) // source param is not projection param
1173
- return null; // -> can't be used as implicit redirection target
1174
- }
1175
- for (const n in params) {
1176
- const pp = params[n];
1177
- const sp = sourceParams[n];
1178
- if (sp) {
1179
- if (sp.default && !pp.default) // param DEFAULT clause not supported yet
1180
- return null; // param is not optional anymore
1181
- const pt = pp.type && resolveUncheckedPath( pp.type, 'type', pp );
1182
- const st = sp.type && resolveUncheckedPath( sp.type, 'type', sp );
1183
- if ((pt || null) !== (st || null))
1184
- return null; // params have different type
1185
- }
1186
- else if (!pp.default) {
1187
- return null;
1188
- } // non-optional param in projection, but not source
1189
- }
1190
- return source;
1191
- }
1192
-
1193
- function postProcessArtifact( art ) {
1194
- tagCompositionTargets( art );
1195
- if (art.$queries) {
1196
- for (const query of art.$queries) {
1197
- if (query.mixin)
1198
- forEachGeneric( query, 'mixin', tagCompositionTargets );
1199
- }
1200
- }
1201
- if (!art._ancestors || art.kind !== 'entity')
1202
- return; // redirections only to entities
1203
- const service = art._service;
1204
- if (!service)
1205
- return;
1206
- const sname = service.name.absolute;
1207
- art._ancestors.forEach( expose );
1208
- return;
1209
-
1210
- function expose( ancestor ) {
1211
- if (ancestor._service === service)
1212
- return;
1213
- const desc = ancestor._descendants ||
1214
- setLink( ancestor, '_descendants', Object.create(null) );
1215
- if (!desc[sname])
1216
- desc[sname] = [ art ];
1217
- else
1218
- desc[sname].push( art );
1219
- }
1220
- }
1221
-
1222
- function processAspectComposition( base ) {
1223
- // TODO: we need to forbid COMPOSITION of entity w/o keys and ON anyway
1224
- // TODO: consider entity includes
1225
- // TODO: nested containment
1226
- // TODO: better do circular checks in the aspect!
1227
- if (base.kind !== 'entity' || base.query)
1228
- return;
1229
- const keys = baseKeys();
1230
- if (keys)
1231
- forEachGeneric( base, 'elements', expand ); // TODO: recursively here?
1232
- return;
1233
-
1234
- function baseKeys() {
1235
- const k = Object.create(null);
1236
- for (const name in base.elements) {
1237
- const elem = base.elements[name];
1238
- if (elem.$duplicates)
1239
- return false; // no composition-of-type unfold with redefined elems
1240
- if (elem.key && elem.key.val)
1241
- k[name] = elem;
1242
- }
1243
- return k;
1244
- }
1245
-
1246
- function expand( elem ) {
1247
- if (elem.target)
1248
- return;
1249
- let origin = elem;
1250
- // included element do not have target aspect directly
1251
- while (origin && !origin.targetAspect && origin._origin)
1252
- origin = origin._origin;
1253
- let target = origin.targetAspect;
1254
- if (target && target.path)
1255
- target = resolvePath( origin.targetAspect, 'compositionTarget', origin );
1256
- if (!target || !target.elements)
1257
- return;
1258
- const entityName = (isDeprecatedEnabled( options, 'generatedEntityNameWithUnderscore' ))
1259
- ? `${ base.name.absolute }_${ elem.name.id }`
1260
- : `${ base.name.absolute }.${ elem.name.id }`;
1261
- const entity = allowAspectComposition( target, elem, keys, entityName ) &&
1262
- createTargetEntity( target, elem, keys, entityName, base );
1263
- elem.target = {
1264
- location: (elem.targetAspect || elem).location,
1265
- $inferred: 'aspect-composition',
1266
- };
1267
- setLink( elem.target, '_artifact', entity );
1268
- if (entity) {
1269
- model.$compositionTargets[entity.name.absolute] = true;
1270
- processAspectComposition( entity );
1271
- processLocalizedData( entity );
1272
- }
1273
- }
1274
- }
1275
-
1276
- function allowAspectComposition( target, elem, keys, entityName ) {
1277
- if (!target.elements || Object.values( target.elements ).some( e => e.$duplicates ))
1278
- return false; // no elements or with redefinitions
1279
- const location = elem.target && elem.target.location || elem.location;
1280
- if ((elem._main._upperAspects || []).includes( target ))
1281
- return 0; // circular containment of the same aspect
1282
-
1283
- const keyNames = Object.keys( keys );
1284
- if (!keyNames.length) {
1285
- // TODO: for "inner aspect-compositions", signal already in type
1286
- error( null, [ location, elem ], { target },
1287
- 'An aspect $(TARGET) can\'t be used as target in an entity without keys' );
1288
- return false;
1289
- }
1290
- // if (keys.up_) { // only to be tested if we allow to provide a prefix, which could be ''
1291
- // // Cannot be in an "inner aspect-compositions" as it would already be wrong before
1292
- // // TODO: if anonymous type, use location of "up_" element
1293
- // // FUTURE: add sub info with location of "up_" element
1294
- // message( 'id', [location, elem], { target, name: 'up_' }, 'Error',
1295
- // 'An aspect $(TARGET) can't be used as target in an entity with a key named $(NAME)' );
1296
- // return false;
1297
- // }
1298
- if (target.elements.up_) {
1299
- // TODO: for "inner aspect-compositions", signal already in type
1300
- // TODO: if anonymous type, use location of "up_" element
1301
- // FUTURE: if named type, add sub info with location of "up_" element
1302
- error( null, [ location, elem ], { target, name: 'up_' },
1303
- 'An aspect $(TARGET) with an element named $(NAME) can\'t be used as target' );
1304
- return false;
1305
- }
1306
- if (model.definitions[entityName]) {
1307
- error( null, [ location, elem ], { art: entityName },
1308
- // eslint-disable-next-line max-len
1309
- 'Target entity $(ART) can\'t be created as there is another definition with this name' );
1310
- return false;
1311
- }
1312
- const names = Object.keys( target.elements )
1313
- .filter( n => n.startsWith('up__') && keyNames.includes( n.substring(4) ) );
1314
- if (names.length) {
1315
- // FUTURE: if named type, add sub info with location of "up_" element
1316
- error( null, [ location, elem ], { target: entityName, names }, {
1317
- std: 'Key elements $(NAMES) can\'t be added to $(TARGET) as these already exist',
1318
- one: 'Key element $(NAMES) can\'t be added to $(TARGET) as it already exist',
1319
- });
1320
- return false;
1321
- }
1322
- return true;
1323
- }
1324
-
1325
- function createTargetEntity( target, elem, keys, entityName, base ) {
1326
- const { location } = elem.targetAspect || elem.target || elem;
1327
- elem.on = {
1328
- location,
1329
- op: { val: '=', location },
1330
- args: [
1331
- augmentPath( location, elem.name.id, 'up_' ),
1332
- augmentPath( location, '$self' ),
1333
- ],
1334
- $inferred: 'aspect-composition',
1335
- };
1336
-
1337
- const elements = Object.create(null);
1338
- const art = {
1339
- kind: 'entity',
1340
- name: { path: splitIntoPath( location, entityName ), absolute: entityName, location },
1341
- location,
1342
- elements,
1343
- $inferred: 'aspect-composition',
1344
- };
1345
- if (target.name) { // named target aspect
1346
- setLink( art, '_origin', target );
1347
- setLink( art, '_upperAspects', [ target, ...(elem._main._upperAspects || []) ] );
1348
- }
1349
- else {
1350
- // TODO: do we need to give the anonymous target aspect a kind and name?
1351
- setLink( art, '_upperAspects', elem._main._upperAspects || [] );
1352
- }
1353
-
1354
- const up = { // elements.up_ = ...
1355
- name: { location, id: 'up_' },
1356
- kind: 'element',
1357
- location,
1358
- $inferred: 'aspect-composition',
1359
- type: augmentPath( location, 'cds.Association' ),
1360
- target: augmentPath( location, base.name.absolute ),
1361
- cardinality: {
1362
- targetMin: { val: 1, literal: 'number', location },
1363
- targetMax: { val: 1, literal: 'number', location },
1364
- location,
1365
- },
1366
- };
1367
- // By default, 'up_' is a managed primary key association.
1368
- // If 'up_' shall be rendered unmanaged, infer the parent
1369
- // primary keys and add the ON condition
1370
- if (isDeprecatedEnabled( options, 'unmanagedUpInComponent' )) {
1371
- addProxyElements( art, keys, 'aspect-composition', target.name && location,
1372
- 'up__', '@odata.containment.ignore' );
1373
- up.on = augmentEqual( location, 'up_', Object.values( keys ), 'up__' );
1374
- }
1375
- else {
1376
- up.key = { location, val: true };
1377
- // managed associations must be explicitly set to not null
1378
- // even if target cardinality is 1..1
1379
- up.notNull = { location, val: true };
1380
- }
1381
- if (isDeprecatedEnabled( options, 'generatedEntityNameWithUnderscore' ))
1382
- setLink( art, '_base', base._base || base );
1383
-
1384
- dictAdd( art.elements, 'up_', up);
1385
- addProxyElements( art, target.elements, 'aspect-composition', target.name && location );
1386
-
1387
- setLink( art, '_block', model.$internal );
1388
- model.definitions[entityName] = art;
1389
- initArtifact( art );
1390
- return art;
1391
- }
1392
-
1393
- function addProxyElements( proxyDict, elements, inferred, location, prefix = '', anno = '' ) {
1394
- // TODO: also use for includeMembers()?
1395
- for (const name in elements) {
1396
- const pname = `${ prefix }${ name }`;
1397
- const origin = elements[name];
1398
- const proxy = linkToOrigin( origin, pname, null, null, location || origin.location );
1399
- proxy.$inferred = inferred;
1400
- if (origin.masked)
1401
- proxy.masked = Object.assign( { $inferred: 'include' }, origin.masked );
1402
- if (origin.key)
1403
- proxy.key = Object.assign( { $inferred: 'include' }, origin.key );
1404
- if (anno)
1405
- annotateWith( proxy, anno );
1406
- dictAdd( proxyDict.elements, pname, proxy );
1407
- }
1408
- }
1409
-
1410
- function tagCompositionTargets( elem ) {
1411
- const type = elem.type && elem.type.path;
1412
- if (elem.target && type && type[0] && type[0].id === 'cds.Composition') {
1413
- // Currently not as sub element
1414
- // Composition always via [{id:'cds.Composition'}] in both CSN and CDL
1415
- const expected = elem.key && elem.key.val ? 'target' : 'compositionTarget';
1416
- const target = resolvePath( elem.target, expected, elem );
1417
- if (target)
1418
- model.$compositionTargets[target.name.absolute] = true;
1419
- }
1420
- forEachGeneric( elem, 'elements', tagCompositionTargets );
1421
- }
1422
-
1423
- /**
1424
- * @param {Function|false} [veryLate]
1425
- */
1426
- function lateExtensions( veryLate ) {
1427
- for (const name in model.$lateExtensions) {
1428
- const art = model.definitions[name];
1429
- const exts = model.$lateExtensions[name];
1430
- if (art && art.kind !== 'namespace') {
1431
- if (art.builtin) {
1432
- for (const ext of exts)
1433
- info( 'anno-builtin', [ ext.name.location, ext ] );
1434
- }
1435
- // created texts entity, autoexposed entity
1436
- if (exts) {
1437
- extendArtifact( exts, art, 'gen' );
1438
- if (veryLate)
1439
- veryLate( art );
1440
- model.$lateExtensions[name] = null; // done
1441
- }
1442
- }
1443
- else if (veryLate) {
1444
- // Complain about unused extensions, i.e. those
1445
- // which do not point to a valid artifact
1446
- for (const ext of exts) {
1447
- delete ext.name.path[0]._artifact; // get message for root
1448
- // TODO: make resolvePath('extend'/'annotate') ignore namespaces
1449
- if (resolvePath( ext.name, ext.kind, ext )) { // should issue error/info
1450
- // should issue error for cds extensions (annotate ok)
1451
- if (art.kind === 'namespace') {
1452
- info( 'anno-namespace', [ ext.name.location, ext ], {},
1453
- 'Namespaces can\'t be annotated' );
1454
- }
1455
- // Builtin annotations would be represented as annotations in to-csn.js
1456
- else if (art.builtin) {
1457
- info( 'anno-builtin', [ ext.name.location, ext ] );
1458
- }
1459
- }
1460
- // TODO: warning for context/service extension on non-correct
1461
- if (ext.kind === 'annotate')
1462
- delete ext.name._artifact; // make it be considered by extendArtifact()
1463
- }
1464
- // create "super" ANNOTATE containing all non-applied ones
1465
- const first = exts[0];
1466
- const { location } = first.name;
1467
-
1468
- /** @type {XSN.Definition} */
1469
- const annotationArtifact = {
1470
- kind: 'annotate',
1471
- name: { path: [ { id: name, location } ], absolute: name, location },
1472
- location: first.location,
1473
- };
1474
-
1475
- if (!model.extensions)
1476
- model.extensions = [];
1477
-
1478
- model.extensions.push(annotationArtifact);
1479
- extendArtifact( exts, annotationArtifact ); // also sets _artifact link in extensions
1480
- // if one of the annotate statement mentions 'returns', assume it
1481
- // TODO: with warning/info?
1482
- for (const ext of exts) {
1483
- if (ext.$syntax === 'returns')
1484
- annotationArtifact.$syntax = 'returns';
1485
- }
1486
- }
1487
- }
1488
- }
1489
-
1490
- function initExtensionsWithoutApplying() {
1491
- // TODO: think of a better function name
1492
- if (!model.extensions)
1493
- model.extensions = [];
1494
-
1495
- for (const name in extensionsDict) {
1496
- const extensions = extensionsDict[name];
1497
-
1498
- for (const ext of extensions) {
1499
- ext.name.absolute = resolveUncheckedPath( ext.name, 'extend', ext );
1500
- // Define annotations of this top-level extension
1501
- defineAnnotations( ext, ext, ext._block );
1502
- // Initialize members and define annotations in sub-elements.
1503
- initMembers( ext, ext, ext._block, true);
1504
- resolveAllArtifactPathsUnchecked( ext );
1505
-
1506
- model.extensions.push(ext);
1507
- }
1508
- }
1509
-
1510
- // `model.definitions` also contains e.g. "includes" that need to be resolved
1511
- forEachDefinition(model, definition => resolveAllArtifactPathsUnchecked(definition));
1512
- forEachGeneric(model, 'vocabularies', resolveAllArtifactPathsUnchecked );
1513
-
1514
- function resolveAllArtifactPathsUnchecked( art ) {
1515
- if (!art)
1516
- return;
1517
-
1518
- checkArtifact(art);
1519
- forEachMemberRecursivelyWithQuery(art, checkArtifact);
1520
- }
1521
-
1522
- // Function for parse.cdl
1523
- /** @param {XSN.Artifact} artifact */
1524
- function checkArtifact( artifact ) {
1525
- // columns are initialized (and made to elements) in the resolver - do init here
1526
- for (const col of artifact.columns || []) {
1527
- if (!col.name)
1528
- col.name = {};
1529
- setMemberParent( col, null, artifact );
1530
- if (col.value)
1531
- recursivelyResolveExpressionCastTypes(col.value, artifact);
1532
- }
1533
-
1534
- resolveTypeUnchecked(artifact, artifact);
1535
-
1536
- if (artifact.items)
1537
- resolveTypeUnchecked(artifact.items, artifact);
1538
-
1539
- for (const include of (artifact.includes || []))
1540
- resolveUncheckedPath(include, 'include', artifact);
1541
-
1542
- if (artifact.returns) {
1543
- const returnType = (artifact.returns.items || artifact.returns);
1544
- if (returnType.type)
1545
- resolveTypeUnchecked(returnType, artifact);
1546
- }
1547
-
1548
- if (artifact.targetAspect) {
1549
- if (artifact.targetAspect.path)
1550
- resolveUncheckedPath(artifact.targetAspect, 'target', artifact);
1551
- else if (artifact.targetAspect.elements) // ad-hoc composition
1552
- forEachMemberRecursivelyWithQuery(artifact.targetAspect, checkArtifact);
1553
- }
1554
- if (artifact.target) {
1555
- if (artifact.target.path)
1556
- resolveUncheckedPath(artifact.target, 'target', artifact);
1557
- else if (artifact.target.elements) // ad-hoc composition
1558
- forEachMemberRecursivelyWithQuery(artifact.target, checkArtifact);
1559
- }
1560
-
1561
- // User provided 'from'
1562
- if (artifact.from) // may be `null` due to EOF
1563
- resolveUncheckedPath(artifact.from, 'from', artifact);
1564
-
1565
- // Calculated 'from'. TODO: for parse-cdl?
1566
- for (const from of (artifact._from || []))
1567
- resolveUncheckedPath(from, 'from', artifact);
1568
- }
1569
-
1570
- /**
1571
- * Recursively resolve `type`s in expressions.
1572
- * This happens e.g. in `cast()` calls.
1573
- *
1574
- * @param {object} expr Expression to check for `type`s.
1575
- * @param {XSN.Artifact} artifact Surrounding artifact, used for error reporting.
1576
- */
1577
- function recursivelyResolveExpressionCastTypes( expr, artifact ) {
1578
- // TODO: named argument, cast in query clauses, cast in filters, ...
1579
- while (Array.isArray(expr)) // old-style XSN paren representation
1580
- expr = expr[0];
1581
- if (expr.args) {
1582
- for (const arg of Array.isArray(expr.args) ? expr.args : Object.values( expr.args ))
1583
- recursivelyResolveExpressionCastTypes(arg, artifact);
1584
- }
1585
- if (expr.type) {
1586
- const name = resolveUncheckedPath( expr.type, 'type', artifact );
1587
- const def = name && model.definitions[name];
1588
- if (def)
1589
- resolveTypeArguments( expr, def, artifact );
1590
- }
1591
- }
1592
-
1593
- /**
1594
- * Resolves `artWithType.type` in an unchecked manner. Handles `type of` cases.
1595
- *
1596
- * @param {object} artWithType
1597
- * @param {XSN.Artifact} artifact
1598
- */
1599
- function resolveTypeUnchecked(artWithType, artifact) {
1600
- if (!artWithType.type)
1601
- return;
1602
- const root = artWithType.type.path && artWithType.type.path[0];
1603
- if (!root) // parse error
1604
- return;
1605
- // `scope` is only `typeOf` for `type of element` and not
1606
- // `type of Entity:element`. For the latter we can resolve the path
1607
- // without special treatment.
1608
- if (artWithType.type.scope !== 'typeOf') {
1609
- // elem: Type or elem: type of Artifact:elem
1610
- const name = resolveUncheckedPath(artWithType.type, 'type', artifact);
1611
- const def = name && model.definitions[name];
1612
- if (def)
1613
- resolveTypeArguments( artWithType, def, artifact );
1614
- return;
1615
- }
1616
- else if (!artifact._main) {
1617
- error( 'ref-undefined-typeof', [ artWithType.type.location, artifact ], {},
1618
- 'Current artifact has no element to refer to as type' );
1619
- return;
1620
- }
1621
- else if (root.id === '$self' || root.id === '$projection') {
1622
- setLink( root, '_artifact', artifact._main );
1623
- }
1624
- else {
1625
- const fake = { name: { absolute: artifact.name.absolute } };
1626
- // to-csn just needs a fake element whose absolute name and _parent/_main links are correct
1627
- setLink( fake, '_parent', artifact._parent );
1628
- setLink( fake, '_main', artifact._main ); // value does not matter...
1629
- setLink( root, '_artifact', fake );
1630
- }
1631
- resolveTypeArguments( artifact, {}, artifact ); // issue error for type args
1632
- }
1633
- }
1634
-
1635
- /**
1636
- * Apply the extensions inside the extensionsDict on the model.
1637
- *
1638
- * Phase 1: context extends, 2: extends with structure includes, 3: extends
1639
- * without structure includes (in the case of cyclic includes)
1640
- *
1641
- * Before phase 1: all artifact extensions have been collected (even those
1642
- * inside extend context), only "empty" ones from structure includes are still unknown.
1643
- * After phase 1, all main artifacts are known, also "empty" extensions are known.
1644
- */
1645
- function applyExtensions() {
1646
- let phase = 1; // TODO: basically remove phase 1
1647
- let extNames = Object.keys( extensionsDict ).sort();
1648
- // Remark: The sort() makes sure that an extend for artifact C.E is applied
1649
- // after the extend for C has been applied (which could have defined C.E).
1650
- // Looping over model.definitions in Phase 1 would miss the `extend
1651
- // context` for a context C.C defined in an `extend context C`.
1652
- //
1653
- // TODO: no need to sort anymore
1654
- while (extNames.length) {
1655
- const { length } = extNames;
1656
- for (const name of extNames) {
1657
- const art = model.definitions[name];
1658
- if (!art || art.kind === 'namespace') {
1659
- model.$lateExtensions[name] = extensionsDict[name];
1660
- delete extensionsDict[name];
1661
- }
1662
- else if (art.$duplicates) { // cannot extend redefinitions
1663
- delete extensionsDict[name];
1664
- }
1665
- else if (phase === 1
1666
- ? extendContext( name, art )
1667
- : extendArtifact( extensionsDict[name], art, phase > 2 )) { // >2: no self-include
1668
- delete extensionsDict[name];
1669
- }
1670
- }
1671
- extNames = Object.keys( extensionsDict ); // no sort() required anymore
1672
- if (phase === 1)
1673
- phase = 2;
1674
- else if (extNames.length >= length)
1675
- phase = 3;
1676
- }
1677
- }
1678
-
1679
- function extendContext( name, art ) {
1680
- // (ext.expectedKind == art.kind) already checked by parser except for context/service
1681
- if (!kindProperties[art.kind].artifacts) {
1682
- // no context or service => warn about context extensions
1683
- for (const ext of extensionsDict[name]) {
1684
- if ([ 'context', 'service' ].includes( ext.expectedKind )) {
1685
- const loc = ext.name.location;
1686
- // TODO: warning is enough
1687
- error( 'extend-with-artifacts', [ loc, ext ], { name, '#': ext.expectedKind }, {
1688
- std: 'Cannot extend non-context / non-service $(NAME) with artifacts',
1689
- service: 'Cannot extend non-service $(NAME) with artifacts',
1690
- context: 'Cannot extend non-context $(NAME) with artifacts',
1691
- });
1692
- }
1693
- }
1694
- return false;
1695
- }
1696
-
1697
- for (const ext of extensionsDict[name]) {
1698
- setProp( ext.name, '_artifact', art );
1699
- checkDefinitions( ext, art, 'elements'); // error for elements etc
1700
- checkDefinitions( ext, art, 'enum');
1701
- checkDefinitions( ext, art, 'actions');
1702
- checkDefinitions( ext, art, 'params');
1703
- defineAnnotations( ext, art, ext._block, ext.kind );
1704
- }
1705
- return true;
1706
- }
1707
-
1708
- /**
1709
- * Extend artifact `art` by `extensions`. `noIncludes` can have values:
1710
- * - false: includes are applied, extend and annotate is performed
1711
- * - true: includes are not applied, extend and annotate is performed
1712
- * - 'gen': no includes and no extensions allowed, annotate is performed
1713
- *
1714
- * @param {XSN.Extension[]} extensions
1715
- * @param {XSN.Definition} art
1716
- * @param {boolean|'gen'} [noIncludes=false]
1717
- */
1718
- function extendArtifact( extensions, art, noIncludes = false) {
1719
- if (!noIncludes && !(canApplyIncludes( art ) && extensions.every( canApplyIncludes )))
1720
- return false;
1721
- if (!art.query) {
1722
- model._entities.push( art ); // add structure with includes in dep order
1723
- art.$entity = ++model.$entity;
1724
- }
1725
- if (!noIncludes && art.includes)
1726
- applyIncludes( art, art );
1727
- extendMembers( extensions, art, noIncludes === 'gen' );
1728
- if (!noIncludes && art.includes) {
1729
- // early propagation of specific annotation assignments
1730
- propagateEarly( art, '@cds.autoexpose' );
1731
- propagateEarly( art, '@fiori.draft.enabled' );
1732
- }
1733
- // TODO: complain about element extensions inside projection
1734
- return true;
1735
- }
1736
-
1737
- /**
1738
- * @param {XSN.Definition} art
1739
- * @param {string} prop
1740
- */
1741
- function propagateEarly( art, prop ) {
1742
- if (art[prop])
1743
- return;
1744
- for (const ref of art.includes) {
1745
- const aspect = ref._artifact;
1746
- if (aspect) {
1747
- const anno = aspect[prop];
1748
- if (anno && (anno.val !== null || !art[prop]))
1749
- art[prop] = Object.assign( { $inferred: 'include' }, anno );
1750
- }
1751
- }
1752
- }
1753
-
1754
- /**
1755
- * @param {XSN.Definition} art
1756
- */
1757
- function canApplyIncludes( art ) {
1758
- if (art.includes) {
1759
- for (const ref of art.includes) {
1760
- const template = resolvePath( ref, 'include', art );
1761
- if (template && template.name.absolute in extensionsDict)
1762
- return false;
1763
- }
1764
- }
1765
- return true;
1766
- }
1767
-
1768
- function extendMembers( extensions, art, noExtend ) {
1769
- // TODO: do the whole extension stuff lazily if the elements are requested
1770
- const elemExtensions = [];
1771
- extensions.sort( compareLayer );
1772
- for (const ext of extensions) {
1773
- // console.log(message( 'id', [ext.location, ext], { art: ext.name._artifact },
1774
- // 'Info', 'EXT').toString())
1775
- if (!('_artifact' in ext.name)) { // not already applied
1776
- setProp( ext.name, '_artifact', art );
1777
- if (noExtend && ext.kind === 'extend') {
1778
- error( 'extend-for-generated', [ ext.name.location, ext ], { art },
1779
- 'You can\'t use EXTEND on the generated $(ART)' );
1780
- continue;
1781
- }
1782
- if (ext.includes) {
1783
- // TODO: currently, re-compiling from gensrc does not give the exact
1784
- // element sequence - we need something like
1785
- // includes = ['Base1',3,'Base2']
1786
- // where 3 means adding the next 3 elements before applying include 'Base2'
1787
- if (art.includes)
1788
- art.includes.push(...ext.includes);
1789
- else
1790
- art.includes = [ ...ext.includes ];
1791
- applyIncludes( ext, art );
1792
- }
1793
- defineAnnotations( ext, art, ext._block, ext.kind );
1794
- // TODO: do we allow to add elements with array of {...}? If yes, adapt
1795
- initMembers( ext, art, ext._block ); // might set _extend, _annotate
1796
- dependsOnSilent(art, ext); // art depends silently on ext (inverse to normal dep!)
1797
- }
1798
- for (const name in ext.elements) {
1799
- const elem = ext.elements[name];
1800
- if (elem.kind === 'element') { // i.e. not extend or annotate
1801
- elemExtensions.push( elem );
1802
- break;
1803
- }
1804
- }
1805
-
1806
- if (ext.columns) // extend projection
1807
- extendColumns( ext, art );
1808
- }
1809
- if (elemExtensions.length > 1)
1810
- reportUnstableExtensions( elemExtensions );
1811
-
1812
- [ 'elements', 'actions' ].forEach( (prop) => {
1813
- const dict = art._extend && art._extend[prop];
1814
- for (const name in dict) {
1815
- let obj = art;
1816
- if (obj.targetAspect)
1817
- obj = obj.targetAspect;
1818
- while (obj.items)
1819
- obj = obj.items;
1820
- const validDict = obj[prop] || prop === 'elements' && obj.enum;
1821
- const member = validDict[name];
1822
- if (!member)
1823
- extendNothing( dict[name], prop, name, art, validDict );
1824
- else if (!(member.$duplicates))
1825
- extendMembers( dict[name], member );
1826
- }
1827
- });
1828
- }
1829
-
1830
- /**
1831
- * Copy columns for EXTEND PROJECTION
1832
- *
1833
- * @param {XSN.Extension} ext
1834
- * @param {XSN.Artifact} art
1835
- */
1836
- function extendColumns( ext, art ) {
1837
- // TODO: consider reportUnstableExtensions
1838
- const { location } = ext.name;
1839
- const { query } = art;
1840
- if (!query) {
1841
- if (art.kind !== 'annotate')
1842
- error( 'extend-columns', [ location, ext ], { art } );
1843
- return;
1844
- }
1845
- if (!query.from || !query.from.path) {
1846
- error( 'extend-columns', [ location, ext ], { art } );
1847
- }
1848
- else {
1849
- if (!query.columns)
1850
- query.columns = [ { location, val: '*' } ];
1851
-
1852
- for (const column of ext.columns) {
1853
- setProp( column, '_block', ext._block );
1854
- query.columns.push(column);
1855
- }
1856
- }
1857
- }
1858
-
1859
- function reportUnstableExtensions( extensions ) {
1860
- // Report 'Warning: Unstable element order due to repeated extensions'.
1861
- // Similar to chooseAssignment(), TODO there: also extra intralayer message
1862
- // as this is a modeling error
1863
- let lastExt = null;
1864
- let open = []; // the "highest" layers
1865
- for (const ext of extensions) {
1866
- const extLayer = layer( ext ) || { realname: '', _layerExtends: Object.create(null) };
1867
- if (!open.length) {
1868
- lastExt = ext;
1869
- open = [ extLayer.realname ];
1870
- }
1871
- else if (extLayer.realname === open[open.length - 1]) { // in same layer
1872
- if (lastExt) {
1873
- message( 'extend-repeated-intralayer', [ lastExt.location, lastExt ] );
1874
- lastExt = null;
1875
- }
1876
- message( 'extend-repeated-intralayer', [ ext.location, ext ] );
1877
- }
1878
- else {
1879
- if (lastExt && (open.length > 1 || !extLayer._layerExtends[open[0]])) {
1880
- // report for lastExt if that is unrelated to other open exts or current ext
1881
- message( 'extend-unrelated-layer', [ lastExt.location, lastExt ], {},
1882
- 'Unstable element order due to other extension in unrelated layer' );
1883
- }
1884
- lastExt = ext;
1885
- open = open.filter( name => !extLayer._layerExtends[name] );
1886
- open.push( extLayer.realname );
1887
- }
1888
- }
1889
- }
1890
- /**
1891
- * @param {XSN.Extension[]} extensions
1892
- * @param {string} prop
1893
- * @param {string} name
1894
- * @param {XSN.Artifact} art
1895
- * @param {object} validDict
1896
- */
1897
- function extendNothing( extensions, prop, name, art, validDict ) {
1898
- for (const ext of extensions) {
1899
- // TODO: use shared functionality with notFound in resolver.js
1900
- const { location } = ext.name;
1901
- const msg
1902
- = error( 'extend-undefined', [ location, ext ],
1903
- { art: searchName( art, name, dictKinds[prop] ) },
1904
- {
1905
- std: 'Unknown $(ART) - nothing to extend',
1906
- // eslint-disable-next-line max-len
1907
- element: 'Artifact $(ART) has no element or enum $(MEMBER) - nothing to extend',
1908
- action: 'Artifact $(ART) has no action $(MEMBER) - nothing to extend',
1909
- } );
1910
- attachAndEmitValidNames(msg, validDict);
1911
- }
1912
- }
1913
-
1914
- /**
1915
- * @param {XSN.Extension} ext
1916
- * @param {XSN.Artifact} art
1917
- */
1918
- function applyIncludes( ext, art ) {
1919
- if (!art._ancestors)
1920
- setProp( art, '_ancestors', [] ); // recursive array of includes
1921
- for (const ref of ext.includes) {
1922
- const template = ref._artifact; // already resolved
1923
- if (template) {
1924
- if (template._ancestors)
1925
- art._ancestors.push( ...template._ancestors );
1926
- art._ancestors.push( template );
1927
- }
1928
- }
1929
- includeMembers( ext, 'elements', forEachInOrder, ext === art && art );
1930
- includeMembers( ext, 'actions', forEachGeneric, ext === art && art );
1931
- }
1932
-
1933
- /**
1934
- * @param {XSN.Extension} ext
1935
- * @param {string} prop
1936
- * @param {function} forEach
1937
- * @param {XSN.Artifact} parent
1938
- */
1939
- function includeMembers( ext, prop, forEach, parent ) {
1940
- // TODO two kind of messages:
1941
- // Error 'More than one include defines element "A"' (at include ref)
1942
- // Warning 'Overwrites definition from include "I" (at elem def)
1943
- const members = ext[prop];
1944
- ext[prop] = Object.create(null); // TODO: do not set actions property if there are none
1945
- for (const ref of ext.includes) {
1946
- const template = ref._artifact; // already resolved
1947
- if (template) { // be robust
1948
- forEach( template, prop, ( origin, name ) => {
1949
- if (members && name in members)
1950
- return; // TODO: warning for overwritten element
1951
- const elem = linkToOrigin( origin, name, parent, prop, weakLocation( ref.location ) );
1952
- if (!parent) // not yet set for EXTEND foo WITH bar
1953
- dictAdd( ext[prop], name, elem );
1954
- elem.$inferred = 'include';
1955
- if (origin.masked)
1956
- elem.masked = Object.assign( { $inferred: 'include' }, origin.masked );
1957
- if (origin.key)
1958
- elem.key = Object.assign( { $inferred: 'include' }, origin.key );
1959
- // TODO: also complain if elem is just defined in art
1960
- });
1961
- }
1962
- }
1963
- // TODO: expand elements having direct elements (if needed)
1964
- if (members) {
1965
- forEach( { [prop]: members }, prop, ( elem, name ) => {
1966
- dictAdd( ext[prop], name, elem );
1967
- });
1968
- }
1969
- }
1970
-
1971
- /**
1972
- * Process "composition of" artifacts.
1973
- *
1974
- * @param {string} name
1975
- */
1976
- function processArtifact( name ) {
1977
- const art = model.definitions[name];
1978
- if (!(art.$duplicates)) {
1979
- processAspectComposition( art );
1980
- if (art.kind === 'entity' && !art.query && art.elements)
1981
- // check potential entity parse error
1982
- processLocalizedData( art );
1983
- }
1984
- }
1985
-
1986
- /**
1987
- * @param {XSN.Artifact} art
1988
- */
1989
- function processLocalizedData( art ) {
1990
- const fioriAnno = art['@fiori.draft.enabled'];
1991
- const fioriEnabled = fioriAnno && (fioriAnno.val === undefined || fioriAnno.val);
1992
-
1993
- const textsName = (isDeprecatedEnabled( options, 'generatedEntityNameWithUnderscore' ))
1994
- ? `${ art.name.absolute }_texts`
1995
- : `${ art.name.absolute }.texts`;
1996
- const textsEntity = model.definitions[textsName];
1997
- const localized = localizedData( art, textsEntity, fioriEnabled );
1998
- if (!localized)
1999
- return;
2000
- if (textsEntity) // expanded localized data in source
2001
- return; // -> make it idempotent
2002
- createTextsEntity( art, textsName, localized, fioriEnabled );
2003
- addTextsAssociations( art, textsName, localized );
2004
- }
2005
-
2006
- /**
2007
- * @param {XSN.Artifact} art
2008
- * @param {XSN.Artifact|undefined} textsEntity
2009
- * @param {boolean} fioriEnabled
2010
- */
2011
- function localizedData( art, textsEntity, fioriEnabled ) {
2012
- let keys = 0;
2013
- const textElems = [];
2014
- const conflictingElements = [];
2015
- const protectedElements = [ 'locale', 'texts', 'localized' ];
2016
- if (fioriEnabled)
2017
- protectedElements.push('ID_texts');
2018
- if (addTextsLanguageAssoc)
2019
- protectedElements.push('language');
2020
-
2021
- for (const name in art.elements) {
2022
- const elem = art.elements[name];
2023
- if (elem.$duplicates)
2024
- return false; // no localized-data unfold with redefined elems
2025
- if (protectedElements.includes( name ))
2026
- conflictingElements.push( elem );
2027
-
2028
- const isKey = elem.key && elem.key.val;
2029
- const isLocalized = hasTruthyProp( elem, 'localized' );
2030
-
2031
- if (isKey) {
2032
- keys += 1;
2033
- textElems.push( elem );
2034
- }
2035
- else if (isLocalized) {
2036
- textElems.push( elem );
2037
- }
2038
-
2039
- if (isKey && isLocalized) { // key with localized is wrong - ignore localized
2040
- const errpos = elem.localized || elem.type || elem.name;
2041
- warning( 'localized-key', [ errpos.location, elem ], { keyword: 'localized' },
2042
- 'Keyword $(KEYWORD) is ignored for primary keys' );
2043
- }
2044
- }
2045
- if (textElems.length <= keys)
2046
- return false;
2047
-
2048
- if (!keys) {
2049
- warning( null, [ art.name.location, art ], {},
2050
- 'No texts entity can be created when no key element exists' );
2051
- return false;
2052
- }
2053
-
2054
- if (textsEntity) {
2055
- if (textsEntity.$duplicates)
2056
- return false;
2057
- if (textsEntity.kind !== 'entity' || textsEntity.query ||
2058
- // already have elements "texts" and "localized" (and optionally ID_texts)
2059
- conflictingElements.length !== 2 || art.elements.locale ||
2060
- (fioriEnabled && art.elements.ID_texts)) {
2061
- // TODO if we have too much time: check all elements of texts entity for safety
2062
- warning( null, [ art.name.location, art ], { art: textsEntity },
2063
- // eslint-disable-next-line max-len
2064
- 'Texts entity $(ART) can\'t be created as there is another definition with that name' );
2065
- info( null, [ textsEntity.name.location, textsEntity ], { art },
2066
- 'Texts entity for $(ART) can\'t be created with this definition' );
2067
- }
2068
- else if (!art._block || art._block.$frontend !== 'json') {
2069
- info( null, [ art.name.location, art ], {},
2070
- 'Localized data expansions has already been done' );
2071
- return textElems; // make double-compilation even with after toHana
2072
- }
2073
- else if (!art._block.$withLocalized && !options.$recompile) {
2074
- art._block.$withLocalized = true;
2075
- info( 'recalculated-text-entities', [ art.name.location, null ], {},
2076
- 'Input CSN contains expansions for localized data' );
2077
- return textElems; // make compilation idempotent
2078
- }
2079
- else {
2080
- return textElems;
2081
- }
2082
- }
2083
- for (const elem of conflictingElements) {
2084
- warning( null, [ elem.name.location, art ], { name: elem.name.id },
2085
- 'No texts entity can be created when element $(NAME) exists' );
2086
- }
2087
- return !textsEntity && !conflictingElements.length && textElems;
2088
- }
2089
-
2090
- /**
2091
- * TODO: set _parent also for main artifacts!
2092
- *
2093
- * @param {XSN.Artifact} base
2094
- * @param {string} absolute
2095
- * @param {XSN.Element[]} textElems
2096
- * @param {boolean} fioriEnabled
2097
- */
2098
- function createTextsEntity( base, absolute, textElems, fioriEnabled ) {
2099
- const elements = Object.create(null);
2100
- const { location } = base.name;
2101
- const art = {
2102
- kind: 'entity',
2103
- name: { path: splitIntoPath( location, absolute ), absolute, location },
2104
- location: base.location,
2105
- elements,
2106
- $inferred: 'localized',
2107
- };
2108
- const locale = {
2109
- name: { location, id: 'locale' },
2110
- kind: 'element',
2111
- type: augmentPath( location, 'cds.String' ),
2112
- length: { literal: 'number', val: 14, location },
2113
- location,
2114
- };
2115
-
2116
- if (!fioriEnabled) {
2117
- locale.key = { val: true, location };
2118
- // To be compatible, we switch off draft without @fiori.draft.enabled
2119
- // TODO (next major version): remove?
2120
- annotateWith( art, '@odata.draft.enabled', art.location, false );
2121
- }
2122
- else {
2123
- const textId = {
2124
- name: { location, id: 'ID_texts' },
2125
- kind: 'element',
2126
- key: { val: true, location },
2127
- type: augmentPath( location, 'cds.UUID' ),
2128
- location,
2129
- };
2130
- dictAdd( art.elements, 'ID_texts', textId );
2131
- }
2132
- if (isDeprecatedEnabled( options, 'generatedEntityNameWithUnderscore' ))
2133
- setProp( art, '_base', base );
2134
-
2135
- dictAdd( art.elements, 'locale', locale );
2136
- if (addTextsLanguageAssoc) {
2137
- const language = {
2138
- name: { location, id: 'language' },
2139
- kind: 'element',
2140
- location,
2141
- type: augmentPath( location, 'cds.Association' ),
2142
- target: augmentPath( location, 'sap.common.Languages' ),
2143
- on: {
2144
- op: { val: '=', location },
2145
- args: [
2146
- { path: [ { id: 'language', location }, { id: 'code', location } ], location },
2147
- { path: [ { id: 'locale', location } ], location },
2148
- ],
2149
- location,
2150
- },
2151
- };
2152
- setProp( language, '_block', model.$internal );
2153
- dictAdd( art.elements, 'language', language );
2154
- }
2155
- setLink( art, '_block', model.$internal );
2156
- model.definitions[absolute] = art;
2157
- initArtifact( art );
2158
-
2159
- // assertUnique array value, first entry is 'locale'
2160
- const assertUniqueValue = [ {
2161
- path: [ { id: locale.name.id, location: locale.location } ],
2162
- location: locale.location,
2163
- } ];
2164
-
2165
- for (const orig of textElems) {
2166
- const elem = linkToOrigin( orig, orig.name.id, art, 'elements' );
2167
- if (orig.key && orig.key.val) {
2168
- // elem.key = { val: fioriEnabled ? null : true, $inferred: 'localized', location };
2169
- // TODO: the previous would be better, but currently not supported in toCDL
2170
- if (!fioriEnabled) {
2171
- elem.key = { val: true, $inferred: 'localized', location };
2172
- // If the propagated elements remain key (that is not fiori.draft.enabled)
2173
- // they should be omitted from OData containment EDM
2174
- annotateWith( elem, '@odata.containment.ignore', location );
2175
- }
2176
- else {
2177
- // add the former key paths to the unique constraint
2178
- assertUniqueValue.push({
2179
- path: [ { id: orig.name.id, location: orig.location } ],
2180
- location: orig.location,
2181
- });
2182
- }
2183
- }
2184
- if (hasTruthyProp( orig, 'localized' )) { // use location of LOCALIZED keyword
2185
- const localized = orig.localized || orig.type || orig.name;
2186
- elem.localized = { val: null, $inferred: 'localized', location: localized.location };
2187
- }
2188
- }
2189
- if (fioriEnabled)
2190
- annotateWith( art, '@assert.unique.locale', art.location, assertUniqueValue, 'array' );
2191
- }
2192
-
2193
- /**
2194
- * @param {XSN.Artifact} art
2195
- * @param {string} textsName
2196
- * @param {XSN.Element[]} textElems
2197
- */
2198
- function addTextsAssociations( art, textsName, textElems ) {
2199
- // texts : Composition of many Books.texts on texts.ID=ID;
2200
- /** @type {array} */
2201
- const keys = textElems.filter( e => e.key && e.key.val );
2202
- const { location } = art.name;
2203
- const texts = {
2204
- name: { location, id: 'texts' },
2205
- kind: 'element',
2206
- location,
2207
- $inferred: 'localized-texts',
2208
- type: augmentPath( location, 'cds.Composition' ),
2209
- cardinality: { targetMax: { literal: 'string', val: '*', location }, location },
2210
- target: augmentPath( location, textsName ),
2211
- on: augmentEqual( location, 'texts', keys ),
2212
- };
2213
- setMemberParent( texts, 'texts', art, 'elements' );
2214
- setProp( texts, '_block', model.$internal );
2215
- // localized : Association to Books.texts on
2216
- // localized.ID=ID and localized.locale = $user.locale;
2217
- keys.push( [ 'localized.locale', '$user.locale' ] );
2218
- const localized = {
2219
- name: { location, id: 'localized' },
2220
- kind: 'element',
2221
- location,
2222
- $inferred: 'localized-texts',
2223
- type: augmentPath( location, 'cds.Association' ),
2224
- target: augmentPath( location, textsName ),
2225
- on: augmentEqual( location, 'localized', keys ),
2226
- };
2227
- setMemberParent( localized, 'localized', art, 'elements' );
2228
- setProp( localized, '_block', model.$internal );
2229
- }
2230
-
2231
- /**
2232
- * @param {XSN.Artifact} art
2233
- * @param {string} prop
2234
- */
2235
- function hasTruthyProp( art, prop ) {
2236
- // Returns whether art directly or indirectly has the property 'prop',
2237
- // following the 'origin' and the 'type' (not involving elements).
2238
- //
2239
- // TODO: we should issue a warning if we get localized via TYPE OF
2240
- // TODO XSN: for anno short form, use { val: true, location, <no literal prop> }
2241
- // ...then this function also works with annotations
2242
- const processed = Object.create(null); // avoid infloops with circular refs
2243
- let name = art.name.absolute; // is ok, since no recursive type possible
2244
- while (art && !processed[name]) {
2245
- if (art[prop])
2246
- return art[prop].val;
2247
- processed[name] = art;
2248
- if (art._origin) {
2249
- art = art._origin;
2250
- name = art && art.name.absolute;
2251
- }
2252
- else if (art.type && art._block && art.type.scope !== 'typeOf') {
2253
- // TODO: also do something special for TYPE OF inside `art`s own elements
2254
- name = resolveUncheckedPath( art.type, 'type', art );
2255
- art = name && model.definitions[name];
2256
- }
2257
- else {
2258
- return false;
2259
- }
2260
- }
2261
- return false;
2262
- }
2263
- }
2264
-
2265
- /**
2266
- * Merge (optional) translations into the XSN model.
2267
- *
2268
- * @param {XSN.Model} model
2269
- */
2270
- function mergeI18nBlocks( model ) {
2271
- const sortedSources = Object.keys(model.sources)
2272
- .filter(name => !!model.sources[name].i18n)
2273
- .sort( (a, b) => compareLayer( model.sources[a], model.sources[b] ) );
2274
-
2275
- if (sortedSources.length === 0)
2276
- return;
2277
-
2278
- if (!model.i18n)
2279
- model.i18n = Object.create( null );
2280
-
2281
- for (const name of sortedSources)
2282
- initI18nFromSource( model.sources[name] );
2283
-
2284
- /**
2285
- * Add the source's translations to the model. Warns if the sources translations
2286
- * do not match the ones from previous sources.
2287
- *
2288
- * @param {XSN.AST} src
2289
- */
2290
- function initI18nFromSource( src ) {
2291
- for (const langKey of Object.keys( src.i18n )) {
2292
- if (!model.i18n[langKey])
2293
- model.i18n[langKey] = Object.create( null );
2294
-
2295
- for (const textKey of Object.keys( src.i18n[langKey] )) {
2296
- const sourceVal = src.i18n[langKey][textKey];
2297
- const modelVal = model.i18n[langKey][textKey];
2298
- if (!modelVal) {
2299
- model.i18n[langKey][textKey] = sourceVal;
2300
- }
2301
- else if (modelVal.val !== sourceVal.val) {
2302
- // TODO: put mergeI18nBlocks() into main function instead
2303
- model.$messageFunctions.warning( 'i18n-different-value', sourceVal.location,
2304
- { prop: textKey, otherprop: langKey } );
2305
- }
2306
- }
2307
- }
2308
- }
2309
- }
2310
-
2311
- /**
2312
- * Return string 'A.B.C' for parsed source `A.B.C` (is vector of ids with
2313
- * locations).
2314
- *
2315
- * @param {XSN.Path} path
2316
- */
2317
- function pathName(path) {
2318
- return path.map( id => id.id ).join('.');
2319
- }
2320
-
2321
- function augmentEqual( location, assocname, relations, prefix = '' ) {
2322
- const args = relations.map( eq );
2323
- return (args.length === 1)
2324
- ? args[0]
2325
- : { op: { val: 'and', location }, args, location };
2326
-
2327
- function eq( refs ) {
2328
- if (Array.isArray(refs))
2329
- return { op: { val: '=', location }, args: refs.map( ref ), location };
2330
-
2331
- const { id } = refs.name;
2332
- return {
2333
- op: { val: '=', location },
2334
- args: [
2335
- { path: [ { id: assocname, location }, { id, location } ], location },
2336
- { path: [ { id: `${ prefix }${ id }`, location } ], location },
2337
- ],
2338
- location,
2339
- };
2340
- }
2341
- function ref( path ) {
2342
- return { path: path.split('.').map( id => ({ id, location }) ), location };
2343
- }
2344
- }
2345
-
2346
- // these function could be used to a future lib/compiler/utils.js, but DO NOT
2347
- // SHARE with utility functions for CSN processors
2348
-
2349
- module.exports = { define };