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