001package daikon.tools.jtb;
002
003import static java.nio.charset.StandardCharsets.UTF_8;
004
005import java.io.File;
006import java.io.FileInputStream;
007import java.io.IOException;
008import java.io.Reader;
009import java.io.UncheckedIOException;
010import java.io.Writer;
011import java.nio.file.Files;
012import java.nio.file.Paths;
013import jtb.cparser.*;
014import jtb.cparser.customvisitor.*;
015import jtb.cparser.syntaxtree.*;
016
017public class CreateSpinfoC {
018
019  public static void main(String[] args) {
020    if (args.length == 1) {
021      System.out.println("Create spinfo file from file " + args[0] + " . . .");
022    } else {
023      System.out.println("C Parser Version 0.1Alpha:  Usage is one of:");
024      System.out.println("         java CreateSpinfoC < inputfile");
025      System.out.println("OR");
026      System.out.println("         java CreateSpinfoC inputfile");
027      return;
028    }
029    try {
030      String fileName = args[0].substring(0, args[0].lastIndexOf("."));
031      File temp = new File(fileName + ".temp");
032      // filter out the '\f' characters in the file
033      try (Reader reader = Files.newBufferedReader(Paths.get(args[0]), UTF_8);
034          Writer writer = Files.newBufferedWriter(temp.toPath(), UTF_8)) {
035        int c;
036        while ((c = reader.read()) != -1) {
037          if (c != '\f') {
038            writer.write(c);
039          }
040        }
041      } catch (IOException e) {
042        System.out.println(e.getMessage());
043        if (temp != null) {
044          temp.delete();
045        }
046        System.exit(1);
047        throw new Error("unreachable");
048      }
049      try (FileInputStream fis = new FileInputStream(temp)) {
050        @SuppressWarnings("UnusedVariable") // sets static variables for TranslationUnit()
051        CParser parser = new CParser(fis);
052      } catch (IOException e) {
053        throw new UncheckedIOException("problem reading " + temp, e);
054      }
055      TranslationUnit root = CParser.TranslationUnit();
056      StringFinder finder = new StringFinder();
057      temp.delete();
058      root.accept(finder);
059
060      ConditionPrinter printer;
061      try {
062        printer = new ConditionPrinter(fileName + ".spinfo");
063        printer.setActualStrings(finder.functionStringMapping);
064        printer.setStringArrays(finder.stringMatrices);
065        root.accept(printer);
066        printer.close();
067      } catch (IOException e) {
068        System.out.println("File IO Error");
069        System.out.println(e.getMessage());
070      }
071      System.out.println("CreateSpinfoC:  C program parsed successfully.");
072    } catch (ParseException e) {
073      System.out.println("CreateSpinfoC encountered errors during parse.");
074      System.out.println(e.getMessage());
075    }
076  }
077}