Calling macro incorrectly

I don’t really need help with this, but more wanted to just present this issue.

If you define a macro that is looking for a type declaration, then you call that macro and forget to pass the type_declaration.var, then nothing will happen. This is because of how crystal allows you to define variables in the open space.

abstract class One
  macro foo_bar(type_dec)
    {% raise type_dec.var %}

class Two < One
  # I expected this to call the macro, but it doesn't
  foo_bar : String

In this case, you could call the macro with parenthesis foo_bar( : String). This would raise an error (albeit not the error you’d want). My guess is this isn’t something that could really be fixed, and just a side affect to how crystal works. But I figured I would post this in case it sparks any ideas

cc @Blacksmoke16

I’m not sure I see the issue here?

  • foo_bar : String - This doesn’t call the macro since it thinks you’re just typing a variable called foo_bar

  • foo_bar( : String) - The paren tells it you’re doing a method/macro call, but correctly errors since the TypeDeclaration you passed it doesn’t have a var defined. I.e it’s incomplete.

  • foo_bar(name : String) - Errors with what you want correctly since the paren tells it you want to call the macro and you’re passing it a complete TypeDeclaration.

1 Like


Maybe we could give an error if you do var : Type but then never assign to var. That way you’ll know you might have used var incorrectly. But I don’t know how easy is that (it should be, but you never know).

1 Like

Yeah, not really an issue. This came up from someone working on a lucky app that did

belongs_to : Owner

but forgot to add the type declaration var. The app still compiled, and was throwing a different error. My initial thought was that it shouldn’t have compiled, but that was because I didn’t know you could type a local variable like that.

It would be cool to catch something like that, but I also know that it’s not really a huge issue, so if it doesn’t happen then it’s no worries. :slight_smile:

belongs_to : Owner reads great btw :)

1 Like