1 package edu.uci.eecs.specCompiler.specExtraction;
3 import java.io.BufferedReader;
5 import java.io.FileNotFoundException;
6 import java.io.FileReader;
7 import java.io.IOException;
8 import java.io.LineNumberReader;
9 import java.util.ArrayList;
13 * This class represents the specification extractor of the specification. The
14 * main function of this class is to read C/C++11 source files and extract the
15 * corresponding specification out, and remember its location, including the
16 * file name and the line number, to help the code generation process.
21 public class SpecExtractor {
22 private ArrayList<SpecConstruct> _constructs;
23 private int _beginLineNum, _endLineNum;
24 private String _beginLine;
27 _constructs = new ArrayList<SpecConstruct>();
32 * Given a list of files, it scans each file and add found SpecConstrcut
33 * to the _constructs list.
36 * @throws SpecNotMatchException
38 public void extract(File[] files) throws SpecNotMatchException {
39 for (int i = 0; i < files.length; i++)
43 public void extract(File file) throws SpecNotMatchException {
45 LineNumberReader reader = new LineNumberReader(new FileReader(file));
46 String prevLine = "", curLine, trimedLine;
47 StringBuilder specText = new StringBuilder();
48 boolean foundHead = false;
50 while ((curLine = reader.readLine()) != null) {
51 if (prevLine.endsWith("\\"))
53 trimedLine = trimSpace(curLine);
55 if (trimedLine.startsWith("/**")) {
56 _beginLineNum = reader.getLineNumber();
59 specText.append("\n");
60 specText.append(curLine);
61 if (trimedLine.endsWith("*/")) {
62 _endLineNum = reader.getLineNumber();
65 System.out.println("Spec<" + specIndex + "> Begin: "
66 + _beginLine + " End: " + _endLineNum);
67 System.out.println(specText);
72 specText.append("\n");
73 specText.append(curLine);
74 if (trimedLine.endsWith("*/")) {
75 _endLineNum = reader.getLineNumber();
78 System.out.println("Spec<" + specIndex + "> Begin: "
79 + _beginLine + " End: " + _endLineNum);
80 System.out.println(specText);
83 specText = new StringBuilder();
87 // At the end we can only find the head "/**" but no tail found
89 String msg = "In file \"" + file.getAbsolutePath() + "\", line: "
90 + _beginLineNum + "\n" + _beginLine + "\n" + "Can't find matching spec.";
91 throw new SpecNotMatchException(msg);
93 } catch (FileNotFoundException e) {
95 } catch (IOException e) {
100 private String trimSpace(String line) {
103 for (i = 0; i < line.length(); i++) {
105 if (ch != ' ' && ch != '\t')
108 for (j = line.length() - 1; j >= 0; j--) {
110 if (ch != ' ' && ch != '\t')
116 return line.substring(i, j + 1);
119 public static void main(String[] argvs) {
120 SpecExtractor extractor = new SpecExtractor();
121 File file = new File("./grammer/spec1.txt");
123 extractor.extract(file);
124 } catch (SpecNotMatchException e) {