Say I have a simple context free grammar:
Z = XY
X = ("ab")+
Y = "abc"
My simplified recursive descent parser for this grammar looks like:
// takes an input string and returns the length of match, -1 for failure
int Z(str) {
int len1 = X(str);
if (len1 >= 0) {
int len2 = Y(str.substr(length));
if (len2 >= 0) {
return len1 + len2; // matches
}
}
return -1; // doesn't match
}
int X(str) {
// matches 1 or multiple "ab"
int len = 0;
while (str.startsWith("ab")) {
len += 2;
str = str.substr(2);
}
return len > 0 ? len : -1;
}
int Y(str) {
// matches "abc" exactly
return str.startsWith("abc") ? 3 : -1;
}
The problem is that how can I match "abababc" with this algorithm? It looks like a limitation of recursive descent parser to me, just wanted to confirm, please correct me if my understanding is wrong.
PS: some people mentioned it doesn't need a recursive descent parser, it's a regular expression. I'm interested in understanding the power and limitation of recursive descent parser in this question, not interested in solving it with regular expression. To be more specific, what kind of grammar can be parsed with a recursive descent parser? and what can't.
X = (ab)+
really will be used in the input? Means, that+
plus sign is a real plus,or just an option of at least one or more instances? Please clarify. As the example of input which you gave doesn't contain +... – Am_I_HelpfulX()
andY().
Post your attempts. – user207421X()
andY()
your question is unanswerable. – user207421