How to add an item to an array within an Antlr Context in C#

67 views Asked by At

I'm trying to generate LaTex for PGFPlots graphs using Antlr from a C# project.

So far, I've created this grammar for the axis, which is essentially a set of kvps:

grammar PgfPlots;

axis
    : 'axis' '[' keyValPairs ']'
    ;

keyValPairs
    : (keyValPair)+
    ;

keyValPair
    : Key '=' Value
    ;

Key
    : [a-zA-Z_][a-zA-Z_0-9]*
    ;

Value
    : INT
    | FLOAT
    | STRING
    ;

INT
    : [0-9]+
    ;

FLOAT
    : [0-9]+ '.' [0-9]+
    ;

STRING
    : '"' .*? '"'
    ;

WS
    : [ \t\r\n]+ -> skip
    ;

However, I can't for the life of me work out how to actually populate the AST.

So far, I've tried this:

    public string GenerateSourceCode(PgfPlotDefinition plotDefinition)
    {
        PgfPlotsParser.AxisContext axis = new(null, 0);

        List<KeyValuePair<string, object>> notNullProperties = GetNotNullProperties(plotDefinition.AxisDefinition);

        for (int i = 0; i < notNullProperties.Count; i++)
        {
            KeyValuePair<string, object> kvp = notNullProperties[i];
            axis.keyValPairs().keyValPair().SetValue($"{kvp.Key} = {kvp.Value}", i);
        }

        return axis.GetText();
    }

However, this gives me a null reference exception on the line where I'm trying to assign the kvp to the array, which I guess makes sense, because I've not created it to set the value... I just have no idea how I'm actually meant to do that bit?

0

There are 0 answers