@@ -376,25 +376,57 @@ module Crystal
376
376
defs.try(& .has_key?(name)) || parents.try(& .any?(& .has_def?(name)))
377
377
end
378
378
379
+ record DefInMacroLookup
380
+
381
+ # Looks up a macro with the give name and matching the given args
382
+ # and named_args. Returns:
383
+ # - a `Macro`, if found
384
+ # - `nil`, if not found
385
+ # - `DefInMacroLookup` if not found and a Def was found instead
386
+ #
387
+ # In the case of `DefInMacroLookup`, it means that macros shouldn't
388
+ # be looked up in implicit enclosing scopes such as Object
389
+ # or the Program.
379
390
def lookup_macro (name, args : Array , named_args)
380
- if macros = self .macros.try & .[name]?
391
+ # Macros are always stored in a type's metaclass
392
+ macros_scope = self .metaclass? ? self : self .metaclass
393
+
394
+ if macros = macros_scope.macros.try & .[name]?
381
395
match = macros.find & .matches?(args, named_args)
382
396
return match if match
383
397
end
384
398
385
- instance_type.parents.try & .each do |parent |
386
- parent_macro = parent.metaclass.lookup_macro(name, args, named_args)
399
+ # First check if there are defs at this scope with that name.
400
+ # If so, make that a priority in the lookup and don't consider
401
+ # macro matches.
402
+ if has_def?(name)
403
+ return DefInMacroLookup .new
404
+ end
405
+
406
+ parents.try & .each do |parent |
407
+ parent_macro = parent.lookup_macro(name, args, named_args)
387
408
return parent_macro if parent_macro
388
409
end
389
410
390
411
nil
391
412
end
392
413
414
+ # Looks up macros with the given name. Returns:
415
+ # - an Array of Macro if found
416
+ # - `nil` if not found
417
+ # - `DefInMacroLookup` if not found and some Defs were found instead
393
418
def lookup_macros (name )
394
- if macros = self .macros.try & .[name]?
419
+ # Macros are always stored in a type's metaclass
420
+ macros_scope = self .metaclass? ? self : self .metaclass
421
+
422
+ if macros = macros_scope.macros.try & .[name]?
395
423
return macros
396
424
end
397
425
426
+ if has_def?(name)
427
+ return DefInMacroLookup .new
428
+ end
429
+
398
430
parents.try & .each do |parent |
399
431
parent_macros = parent.lookup_macros(name)
400
432
return parent_macros if parent_macros
@@ -950,6 +982,14 @@ module Crystal
950
982
def vars ?
951
983
@vars
952
984
end
985
+
986
+ def metaclass ?
987
+ true
988
+ end
989
+
990
+ def metaclass
991
+ self
992
+ end
953
993
end
954
994
955
995
# Abstract base type for classes and structs
0 commit comments