7
1
Write a program that, given a context free grammar and a string, returns whether the string is a word of the language defined by the grammar.
Input
Your program should read a context free grammar and an input string in an implementation defined way during runtime. Hardcoding the input is acceptable as long as it is trivial to change the input.
The context free grammar is a set of rules as defined by the regex [A-Z][a-zA-Z]*
, that is: One capital letter denoting the nonterminal to be replaced and an arbitrary number of terminals (minuscules) and nonterminals (capitals) to replace it. The grammar may contain up to 256 rules. The initial symbol is always S
. You may not assume that the grammar is unambigous. The grammar must contain at least one production rule for S
.
The input string must match the regex [a-z]*
. It has a length of no more than 65536 characters.
Output
Output is to be done in an implementation defined manner. Your program must output whether the input string is a word of the language defined by the grammar.
Constraints
- Your program must terminate in reasonable time
- You may not use any libraries that provide parsers or parser generators
- You may not run any program that generates a parser
- You may not use compression utilities or libraries
Scoring
This is code-golf. The submission with the smallest number of bytes wins
Example
The rules
S
SaSb
represent a grammar which defines the language anbn for n≥0. So given string aaabbb
it would indicate that it accepts it, but given string aaabb
it would indicate that it does not accept it.
The ruleset
S
SaSbS
ScSdS
describes the Dyck language. It describes the language of all balanced pairs of ab's. and cd's. For instance, string ababacabdb matches but cabdacb doesn't.