How to parse a program - TypeCobolTeam/TypeCobol GitHub Wiki

How to parse a program

Here's a sample of C# code to parse a Cobol program and check if there is no diagnostics

var typeCobolOptions = new TypeCobolOptions
{
    //Optional, the parser will stop if at least one copy is missing
    //Otherwise it will continue (but expect errors if the copy is really needed)
    HaltOnMissingCopy = true,
};
CompilationProject project = new CompilationProject("MyProject", "root directory", new[] { ".cpy"},  DocumentFormat.RDZReferenceFormat, typeCobolOptions);


//Optional, 
    SourceFileProvider sourceFileProvider = project.SourceFileProvider;
    //do this for all others folder which can contains COPYs
    sourceFileProvider.AddLocalDirectoryLibrary("Path to folder", includeSubdirectories: false, fileExtensions: new[] { ".cpy" }, documentFormat: DocumentFormat.RDZReferenceFormat);

//fileNameToParse.cbl : the whole path is not needed, fileName will be search into sourceFileProvider
var compiler = new FileCompiler(project, "fileNameToParse.cbl", false);
//First Compilation that may end because copies are missing
compiler.CompileOnce();

//Download missing copy - see explanation below
//DownloadMissingCopy();


var diagnostics = compiler.CompilationResultsForProgram.AllDiagnostics();
//There should be no diagnostics
Assert.IsFalse(diagnostics.Any(d => d.Info.Severity == Severity.Error));

//The whole AST is then accessible with compiler.CompilationResultsForProgram.ProgramClassDocumentSnapshot.Root

Note that there is a diagnostic for each copy missing.

So if you need to download your copy from a remote location (Librarian, RTC, Git, ...) you can download them and then parse the program again.

private void DownloadMissingCopy(FileCompiler compiler)
{
            var missingCopies = compiler.CompilationResultsForProgram.MissingCopies;
            if (missingCopies.Count > 0) {
                //Retrieve all copies missing
                foreach (var copyDirective in missingCopies) {
                     //Download copy
                     //CopyName = copyDirective.TextName
                }

                //Compile a second time with all copys
                compiler.CompileOnce();
            }
}