Search code examples
objective-ciosgrammarparsekit

Parsekit autocompletion


Given a simple Parsekit grammar.

@start = sentence+;
sentence = 'beer' container;
container = 'bottle' | 'cup';

If I have a partial parse beer is it possible to get Parsekit to return the possible completions to the sentence?


Solution

  • Developer of ParseKit here. 

    Unfortunately, there is no "free" mechanism in ParseKit which will return this data by itself. 

    However, this is exactly the kind of task ParseKit is designed/well-suited for. But you must write some code yourself. Something like this would work:

    First, change the grammar slightly to include a named production for 'beer'. This will make it easier to implement a callback:

    @start = sentence+;
    sentence = beer container;
    beer = 'beer';
    container = 'bottle' | 'cup';
    

    Then  implement an assembler callback for the beer production.

    - (void)parser:(PKParser *)p didMatchBeer:(PKAssembly *)a {
    
        // here you could find some clever way to look up the completions for 'beer' prefix
        // or you can hardcode the completions yourself
        NSArray *completions = [NSArray arrayWithObjects:@"bottle", @"cup", nil];
    
        // store the completions as the current assembly's target
        a.target = completions;
    }
    

    Your 'client' or 'driver' code should look like:

    PKParser *p = [PKParserFactory parserFromGrammar:g assembler:a];
    
    PKAssembly *input = [PKAssembly assemblyWithString:@"beer"]; // get this string from the user in reality
    PKAssembly *result = [p bestMatchFor:input];
    NSArray *completions = result.target;
    

    This should give you an idea of how these types of things can be implemented with ParseKit. For such a small example this solution may look like overkill (and it probably is). But for a large real-world example this would be a very powerful and elegant solution for autocompletion.