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;
11 import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Text;
15 * This class represents the specification extractor of the specification. The
16 * main function of this class is to read C/C++11 source files and extract the
17 * corresponding specification out, and remember its location, including the
18 * file name and the line number, to help the code generation process.
23 public class SpecExtractor {
24 private ArrayList<SpecConstruct> _constructs;
25 private int _beginLineNum, _endLineNum;
26 private String _beginLine;
29 _constructs = new ArrayList<SpecConstruct>();
34 * Given a list of files, it scans each file and add found SpecConstrcut
35 * to the _constructs list.
38 * @throws SpecNotMatchException
40 public void extract(File[] files) throws SpecNotMatchException {
41 for (int i = 0; i < files.length; i++)
45 public void extract(File file) throws SpecNotMatchException {
47 LineNumberReader reader = new LineNumberReader(new FileReader(file));
48 String prevLine = "", curLine, trimedLine;
49 StringBuilder specText = new StringBuilder();
50 boolean foundHead = false;
52 while ((curLine = reader.readLine()) != null) {
53 if (prevLine.endsWith("\\"))
55 trimedLine = trimSpace(curLine);
57 if (trimedLine.startsWith("/**")) {
58 _beginLineNum = reader.getLineNumber();
61 specText.append("\n");
62 specText.append(curLine);
63 if (trimedLine.endsWith("*/")) {
64 _endLineNum = reader.getLineNumber();
67 System.out.println("Spec<" + specIndex + "> Begin: "
68 + _beginLine + " End: " + _endLineNum);
69 System.out.println(specText);
74 specText.append("\n");
75 specText.append(curLine);
76 if (trimedLine.endsWith("*/")) {
77 _endLineNum = reader.getLineNumber();
80 System.out.println("Spec<" + specIndex + "> Begin: "
81 + _beginLine + " End: " + _endLineNum);
82 System.out.println(specText);
85 specText = new StringBuilder();
89 // At the end we can only find the head "/**" but no tail found
91 String msg = "In file \"" + file.getAbsolutePath() + "\", line: "
92 + _beginLineNum + "\n" + _beginLine + "\n" + "Can't find matching spec.";
93 throw new SpecNotMatchException(msg);
95 } catch (FileNotFoundException e) {
97 } catch (IOException e) {
102 private String trimSpace(String line) {
105 for (i = 0; i < line.length(); i++) {
107 if (ch != ' ' && ch != '\t')
110 for (j = line.length() - 1; j >= 0; j--) {
112 if (ch != ' ' && ch != '\t')
118 return line.substring(i, j + 1);
121 public static void main(String[] argvs) {
122 SpecExtractor extractor = new SpecExtractor();
123 File file = new File("./grammer/spec1.txt");
125 extractor.extract(file);
126 } catch (SpecNotMatchException e) {