0

I'm working on a new pet project and i came across this error when trying to store functions in a hash in zig.
the error happens on the try p.nud_handlers.put(Tokens.IDENT, p.parseIdentifier); line

the thing is, i do have the parseIdentifier defined inside of the Parser struct

Stuff that i tried:

  • Defining the function outside of the parse struct. (Whilst this did work, i would like to declare the function inside of the struct)
  • Appending the function to the hash inside of some other function that isnt init (Did not work, same error)

Zig version is 0.15.0 (Master)

error:
parser.zig:102:48: error: no field named 'parseIdentifier' in struct 'parser.Parser'
        try p.nud_handlers.put(Tokens.IDENT, p.parseIdentifier);
const NudParseFn = *const fn (*Parser) *AST.Expression;
const LedParseFn = *const fn (*Parser, *AST.Expression) *AST.Expression;

pub const Parser = struct {
    lexer: *Lexer,
    cur_token: Token = undefined,
    peek_token: Token = undefined,
    nud_handlers: std.AutoHashMap(Tokens, NudParseFn) = undefined,
    led_handlers: std.AutoHashMap(Tokens, LedParseFn) = undefined,

    pub fn init(lexer: *Lexer) !Parser {
        var parser: Parser = Parser{ .lexer = lexer };

        parser.nud_handlers = std.AutoHashMap(Tokens, NudParseFn).init(std.heap.page_allocator);
        parser.led_handlers = std.AutoHashMap(Tokens, LedParseFn).init(std.heap.page_allocator);

       // ... some other code here

        try p.nud_handlers.put(Tokens.IDENT, parser.parseIdentifier); // the error happens here

        return parser;
    }

    pub fn parseIdentifier(p: *Parser) *AST.Expression {
        return &AST.Expression{ .identifier_expr = AST.Identifier{ .token = p.cur_token, .literal = p.cur_token.literal } };
    }
    // Other definitions below...

}

1 Answer 1

0

Inside of the definition of Parser the function can be reffered to by just it's name parseIdentifier, it's directly in scope.

It's also available by referring to it by it's path Parser.parseIdentifier, parser.Parser.parseIdentifier, etc. which also works from outside of the struct definition.

Sign up to request clarification or add additional context in comments.

1 Comment

You're not calling the function, you're passing it as a function pointer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.