Skip to content

Instantly share code, notes, and snippets.

@kssreeram
Created June 28, 2016 07:27
Show Gist options
  • Save kssreeram/a6f094c9caa8ed62461d29f398631fd0 to your computer and use it in GitHub Desktop.
Save kssreeram/a6f094c9caa8ed62461d29f398631fd0 to your computer and use it in GitHub Desktop.
Handling C ambiguity
Modeling C Ambiguity.
@kssreeram
Copy link
Author

How can we model the AST for the following C expression?

(b)-d

It’s confusing because, if b is a type, then the above is a unary negation, and if b is a value, then it is a binary subtraction.

The solution is to ignore the meaning of “-“, and treat it a bit more literally and call it a “hyphen” node in the AST.

struct Hyphen {
    Node *left; // ‘left’ can be NULL
    Node *right;
);

This Hyphen node can represent both meanings of the above expression. The ‘left’ field is optional in order to accomodate all unary uses too.

Once, the AST is built, it’s straight-forward to write a function to test whether a node is a type or a value (by using the symbol table). We can use this function to resolve the meaning of the Hyphen node.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment