GCCSourceAnalysis.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package de.jplag.cpp.experimental;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.*;
  7. /**
  8. * Uses GCC to find unused variables and saves their location. The scanner can then check if a token belongs to an
  9. * unused variable
  10. */
  11. public class GCCSourceAnalysis implements SourceAnalysis {
  12. public static final String COMPILE_COMMAND = "gcc -Wall -fsyntax-only %s";
  13. private Map<String, List<Integer>> linesToDelete = new HashMap<>();
  14. public boolean isTokenIgnored(de.jplag.cpp.Token token, File file) {
  15. String fileName = file.getName();
  16. if (linesToDelete.containsKey(fileName)) {
  17. var ignoredLineNumbers = linesToDelete.get(fileName);
  18. return ignoredLineNumbers.contains(token.beginLine);
  19. }
  20. return false;
  21. }
  22. public void findUnusedVariableLines(Set<File> files) {
  23. linesToDelete = new HashMap<>();
  24. for (File file : files) {
  25. try {
  26. Runtime runtime = Runtime.getRuntime();
  27. Process gcc = runtime.exec(COMPILE_COMMAND.formatted(file.getAbsolutePath()));
  28. gcc.waitFor();
  29. // gcc prints compiler warnings to the error stream, not the standard stream
  30. BufferedReader stdError = new BufferedReader(new InputStreamReader(gcc.getErrorStream()));
  31. String line;
  32. while ((line = stdError.readLine()) != null) {
  33. processOutputLine(line);
  34. }
  35. } catch (IOException | InterruptedException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }
  40. private void processOutputLine(String line) {
  41. // example output:
  42. // sourceFile.c:151:8: warning: unused variable 't' [-Wunused-variable]
  43. if (!line.contains("unused variable")) {
  44. return;
  45. }
  46. // contains [sourceFile, line, column, (warning|error), description]
  47. var lineSplit = line.split(":");
  48. String fileName = new File(lineSplit[0]).getName();
  49. int lineNumber = Integer.parseInt(lineSplit[1]);
  50. if (linesToDelete.containsKey(fileName)) {
  51. linesToDelete.get(fileName).add(lineNumber);
  52. } else {
  53. linesToDelete.put(fileName, new ArrayList<>(lineNumber));
  54. }
  55. }
  56. }