0

I've many question like this before, but every solution I've found involves the usage of indexOf. Just like here.

Well, I'm implementing a recursive descent parser, and after execution each production I've to print the production, something like "A = B 'token' (value of token) C". The problem arises when productions have many other productions and tokens, if I print it in the begining of the production I don't have the value of every token, if I print it in the end the final list of productions will be in an incorrect order.

So I'm doing something like this:

String s="";
productions.add(s);
A();
getToken();
B();
s=("A 'token' B");

You can see that in the method A() I might have something like that too, so I will be addind many s="" to the list, thus indexOf wont work. Currently I'm doing this:

String s="";
s+= productions.size();
productions.add(s);
A();
getToken();
B();
s=("A 'token' B");

But I don't find this solution anyhow elegant. There is a better way to do that?

Here is an example of what I'm trying to do, note that it won't work because you need a lexical analyser that implements the nextToken method

public class parser {
    ArrayList<String> productions = new ArrayList<>();
    void S(){
        //S = A '*' B
        String s="";
        productions.add(s);
        A();
        nextToken();
        B();
        s="S = A '*' B"
        printProductions();
    }

    void A(){
        //A = 'ctn' | B
        String s="";
        productions.add(s);
        if(!currentTk=ctn){
            s="A = B
            B();
        }else{
            s="A = 'ctn'
        }
    }

    void B(){
        //B = 'ctn' '+' 'ctn'
        String s="";
        productions.add(s);
        if(currentTk=ctn){
            nextToken();
            if(currentTk=ctn){
                if(currentTk=ctn){
                    nextToken();
                    s= "'ctn' '+' 'ctn'"
                }
            }
        }
    }
}
3
  • 3
    It's very unclear to me what you're trying to achieve - particularly as you're just assigning a literal string at the end, after calling the unknown A(), B() and getToken() methods, ignoring any results. It would be much easier to help you if you'd post a minimal reproducible example. Commented Oct 15, 2016 at 16:32
  • Hey, the objective here is to write out the syntax tree, for that I need to print the productions (A, B,...) in the order they are accessed. Commented Oct 15, 2016 at 17:12
  • Nope, I'm afraid that doesn't help to clarify your question for me. I still recommend posting a minimal reproducible example. Commented Oct 15, 2016 at 17:15

0

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.