How to read data from a program - TypeCobolTeam/TypeCobol GitHub Wiki

We assume that the code to parse a program is already in place (see How to parse a program).

The best way to read a specific data in a parsed source file, is by implementing a Visitor.

The first step is to create a class extending AbstractAstVisitor that contains overridden Visit() methods. Here is an example that reads DataDescriptions and DataRedefines (all the readable nodes can be found in the folder TypeCobol/Compiler/Nodes):

public class Visitor : AbstractAstVisitor
{
    // Visits all data definitions e.g. "01 VAR PIC 9(5) COMP"
    public override bool Visit(DataDescription node)
    {
        //node.CodeElement gives you the generic CodeElement while node.CodeElement() 
        //casts the CE into the corresponding one (here DataDescriptionEntry).
        //Almost every information from the sourcefile are stored either in the node or in its CodeElement 
        DataDescriptionEntry dataEntry = node.CodeElement();
        DataType type = dataEntry.DataType;

        //Some values need to be checked if they are specified in the sourcefile
        if (dataEntry.LevelNumber != null)
        {
            long level = dataEntry.LevelNumber.Value;
        }

        if (dataEntry.MaxOccurencesCount != null)
        {
            long maxOccurence = dataEntry.MaxOccurencesCount.Value;
        }

        if (node.Picture != null)
        {
            string pic = node.Picture.Value;
        }

        if (node.Usage.HasValue)
        {
            DataUsage usage = node.Usage.Value;
        }

        return true;
    }

    // Visits all data redefines e.g. "05 STR2 REDEFINES STR1."
    public override bool Visit(DataRedefines node)
    {
        DataRedefinesEntry dataEntry = node.CodeElement();
        DataType type = dataEntry.DataType;
        string redefinedVar = dataEntry.RedefinesDataName.Name;

        return true;
    }
}

Every Node has its corresponding CodeElement. Considering the fact the great majority of the information is stored into the CodeElement, you may find the information you need in it. However, each CodeElements doesn't contain the same information. Be assured that you visit the right Node.

The second step is to say to the parsed document that he can be visited. To do this, you need to have access to the document. In the source given in How to parse a program, add the following line at the end of the code:

compiler.CompilationResultsForProgram.ProgramClassDocumentSnapshot.Root.AcceptASTVisitor(new Visitor());

Here you are, by running the program, you can now access the content of your file.