Search code examples
compiler-constructionocamlyaccocamlyacc

Get list in grammar


I'm trying to build a compiler and am quite lost at the moment. I have a main class and want to be able to declare additional classes with inheritance, i.e class newClass extends classThatHasBeenDeclaredBefore { } My input looks like

input:    
    class_main class_list { /* New program created */ }

and my class_list consists of all my classes in my program, it can also be empty.

A simple class is declared like this:

class_decl:
    CLASS_KWORD CLASS_ID
        OPENCURLYBRACE 
            attributes_list
            method_list
        CLOSEDCURLYBRACE { /* Ok new class is created */}

    | CLASS_KWORD CLASS_ID EXTENDS_KWORD CLASS_ID
        OPENCURLYBRACE 
            attributes_list
            method_list
        CLOSEDCURLYBRACE { /* Has CLASS_ID Number 2 been declared before? */ }
;

Is there any way I can check if the second CLASS_ID has already been declared or used before somehow? My thought is that my class_list is inreachable from where I try to add my new class, but I suck at OCaml.


Solution

  • A clean way to handle problems like this is to make an abstract syntax tree from the input. Then you can apply semantic checks to it at your leisure.

    If you want to do all your checking during the parse, you'll have to define your grammar carefully to allow it, and pass around data structures defining what you've seen so far.