@@ -17,11 +17,15 @@ import {
1717} from 'langium' ;
1818import { match } from 'ts-pattern' ;
1919import {
20+ AttributeArg ,
2021 BinaryExpr ,
22+ DataModel ,
2123 Expression ,
2224 MemberAccessExpr ,
25+ isAttributeArg ,
2326 isCollectionPredicateBinding ,
2427 isDataField ,
28+ isDataFieldAttribute ,
2529 isDataModel ,
2630 isEnumField ,
2731 isInvocationExpr ,
@@ -132,6 +136,13 @@ export class ZModelScopeProvider extends DefaultScopeProvider {
132136 if ( containerCollectionPredicate ) {
133137 return this . getCollectionPredicateScope ( context , containerCollectionPredicate ) ;
134138 }
139+
140+ // @relation (fields: [], references: [])
141+ // `references` should include the target model's fields instead of the current model's
142+ const targetModel = this . getTransitiveFieldReferenceTargetModel ( context ) ;
143+ if ( targetModel ) {
144+ return this . getTransitiveFieldReferenceScope ( targetModel ) ;
145+ }
135146 }
136147
137148 return super . getScope ( context ) ;
@@ -264,6 +275,46 @@ export class ZModelScopeProvider extends DefaultScopeProvider {
264275 . otherwise ( ( ) => EMPTY_SCOPE ) ;
265276 }
266277
278+ private getTransitiveFieldReferenceScope ( dm : DataModel ) {
279+ return this . createScope (
280+ getAllFields ( dm ) . map ( ( field ) => this . descriptions . createDescription ( field , field . name ) ) ,
281+ ) ;
282+ }
283+
284+ private getTransitiveFieldReferenceTargetModel ( context : ReferenceInfo ) {
285+ let current : AstNode | undefined = context . container ;
286+ while ( current ) {
287+ if ( isAttributeArg ( current ) ) {
288+ const attr = current . $container ;
289+ if ( ! isDataFieldAttribute ( attr ) ) {
290+ return undefined ;
291+ }
292+
293+ const decl = attr . decl . ref ;
294+ if ( ! decl ) {
295+ return undefined ;
296+ }
297+
298+ const param = current . name
299+ ? decl . params . find ( ( p ) => p . name === ( current as AttributeArg ) . name )
300+ : decl . params [ attr . args . indexOf ( current ) ] ;
301+ if ( param ?. type ?. type !== 'TransitiveFieldReference' ) {
302+ return undefined ;
303+ }
304+
305+ const field = attr . $container ;
306+ if ( ! isDataField ( field ) ) {
307+ return undefined ;
308+ }
309+
310+ const targetType = field . type ?. reference ?. ref ;
311+ return isDataModel ( targetType ) ? targetType : undefined ;
312+ }
313+ current = current . $container ;
314+ }
315+ return undefined ;
316+ }
317+
267318 private createScopeForContainingModel ( node : AstNode , globalScope : Scope ) {
268319 const model = AstUtils . getContainerOfType ( node , isDataModel ) ;
269320 if ( model ) {
0 commit comments