fixed command line
[cdsspec-compiler.git] / src / edu / uci / eecs / codeGenerator / CodeGenerator.java
1 package edu.uci.eecs.codeGenerator;
2
3 import java.io.BufferedReader;
4 import java.io.File;
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;
10 import java.util.Collections;
11 import java.util.HashMap;
12
13 import edu.uci.eecs.codeGenerator.CodeAdditions.CodeAddition;
14 import edu.uci.eecs.specExtraction.Code;
15 import edu.uci.eecs.specExtraction.Construct;
16 import edu.uci.eecs.specExtraction.DefineConstruct;
17 import edu.uci.eecs.specExtraction.EntryConstruct;
18 import edu.uci.eecs.specExtraction.InterfaceConstruct;
19 import edu.uci.eecs.specExtraction.OPConstruct;
20 import edu.uci.eecs.specExtraction.SpecExtractor;
21 import edu.uci.eecs.specExtraction.SpecNaming;
22 import edu.uci.eecs.specExtraction.WrongAnnotationException;
23 import edu.uci.eecs.utilParser.ParseException;
24
25 /**
26  * <p>
27  * This class represents the engine to generate instrumented code. To construct
28  * an object of this file, users need provide a string that represents the
29  * sub-directory under the benchmarks directory, then the engine will explore
30  * all the C/C++ files that ends with ".cc/.cpp/.c/.h" and extract specification
31  * annotations and generate instrumented code in the generated directory.
32  * </p>
33  * 
34  * @author Peizhao Ou
35  * 
36  */
37 public class CodeGenerator {
38         // Files that we need to process
39         private ArrayList<File> files;
40
41         // Code addition list --- per file
42         private ArrayList<CodeAdditions> allAdditions;
43         // Line change map list --- per file; Each map represents the
44         // line->InterfaceConstruct mapping that will rename the interface
45         // declaration line.
46         private ArrayList<HashMap<Integer, InterfaceConstruct>> renamedLinesMapList;
47
48         // The string that users provide as a sub-directory in the benchmarks
49         // directory: e.g. ms-queue
50         public final String dirName;
51
52         // The original directory --- the benchmarks directory: e.g.
53         // ~/model-checker/benchmarks/
54         public final String originalDir;
55         // The directory for generated files: e.g. ~/model-checker/test-cdsspec/
56         public final String generatedDir;
57
58         // The specification annotation extractor
59         private SpecExtractor extractor;
60
61         public CodeGenerator(String originalDir, String generatedDir, String dirName) {
62                 this.dirName = dirName;
63                 this.originalDir = originalDir + "/" + dirName + "/";
64                 this.generatedDir = generatedDir + "/" + dirName + "/";
65                 
66                 //this.originalDir = Environment.BenchmarksDir + dirName + "/";
67                 //this.generatedDir = Environment.GeneratedFilesDir + dirName + "/";
68                 
69                 try {
70                         files = this.getSrcFiles(originalDir);
71                 } catch (FileNotFoundException e) {
72                         e.printStackTrace();
73                 }
74                 extractor = new SpecExtractor();
75                 try {
76                         extractor.extract(files);
77                 } catch (WrongAnnotationException e) {
78                         e.printStackTrace();
79                 } catch (ParseException e) {
80                         e.printStackTrace();
81                 }
82         }
83
84         /**
85          * <p>
86          * This function initializes the list of code additions and line changes for
87          * all the files. For the code additions of a file, we sort them in an
88          * increasing order by the inserting line number.
89          * </p>
90          * 
91          */
92         private void getAllCodeChanges() {
93                 allAdditions = new ArrayList<CodeAdditions>();
94                 renamedLinesMapList = new ArrayList<HashMap<Integer, InterfaceConstruct>>();
95                 for (int i = 0; i < files.size(); i++) {
96                         File file = files.get(i);
97                         // One CodeAdditions per file
98                         CodeAdditions additions = new CodeAdditions(file);
99                         // Add the additions for this file to the list
100                         allAdditions.add(additions);
101
102                         // One CodeChange per file
103                         HashMap<Integer, InterfaceConstruct> renamedLinesMap = new HashMap<Integer, InterfaceConstruct>();
104                         // Add it the the list
105                         renamedLinesMapList.add(renamedLinesMap);
106
107                         // Extract all the additions
108                         ArrayList<OPConstruct> OPList = extractor.OPListMap.get(file);
109                         EntryConstruct entry = extractor.entryMap.get(file);
110                         ArrayList<DefineConstruct> defineList = extractor.defineListMap
111                                         .get(file);
112                         ArrayList<InterfaceConstruct> interfaceList = extractor.interfaceListMap
113                                         .get(file);
114                         Code code = null;
115                         CodeAddition addition = null;
116                         // For ordering point constructs
117                         if (OPList != null) {
118                                 for (OPConstruct con : OPList) {
119                                         code = CodeGeneratorUtils.Generate4OPConstruct(con);
120                                         addition = new CodeAddition(con.beginLineNum, code);
121                                         additions.addCodeAddition(addition);
122                                 }
123                         }
124                         // For entry constructs
125                         if (entry != null) {
126                                 code = CodeGeneratorUtils.Generate4Entry(entry);
127                                 addition = new CodeAddition(entry.beginLineNum, code);
128                                 additions.addCodeAddition(addition);
129                         }
130                         // For define constructs
131                         if (defineList != null) {
132                                 for (DefineConstruct con : defineList) {
133                                         code = CodeGeneratorUtils.Generate4Define(con);
134                                         addition = new CodeAddition(con.endLineNum, code);
135                                         additions.addCodeAddition(addition);
136                                 }
137                         }
138                         // For interface constructs
139                         if (interfaceList != null) {
140                                 for (InterfaceConstruct con : interfaceList) {
141                                         code = CodeGeneratorUtils.GenerateInterfaceWrapper(con);
142                                         addition = new CodeAddition(con.getEndLineNumFunction(),
143                                                         code);
144                                         additions.addCodeAddition(addition);
145                                         // Record the line to be changed
146                                         renamedLinesMap.put(con.endLineNum + 1, con);
147                                 }
148                         }
149
150                         // Sort additions by line number increasingly
151                         additions.sort();
152                 }
153         }
154
155         /**
156          * <p>
157          * For a specific file, given the code additions and line changes mapping
158          * for that file, this function will generate the new code for that file and
159          * write it back to the destination directory.
160          * </p>
161          * 
162          * @param file
163          *            The file to be processed
164          * @param additions
165          *            The sorted code additions for the file
166          * @param renamedLinesMap
167          *            The line change mapping for the file
168          */
169         private void writeCodeChange(File file, CodeAdditions additions,
170                         HashMap<Integer, InterfaceConstruct> renamedLinesMap) {
171                 Code newCode = new Code();
172                 BufferedReader br = null;
173                 LineNumberReader lineReader = null;
174                 int lineNum = 0;
175                 String curLine = null;
176
177                 String dest = generatedDir + file.getName();
178                 CodeAddition curAddition = null;
179                 int additionIdx = -1;
180                 if (!additions.isEmpty()) {
181                         additionIdx = 0;
182                         curAddition = additions.codeAdditions.get(0);
183                 }
184
185                 // Include the header for C/C++ files (.c/.cc/.cpp)
186                 String name = file.getName();
187                 if (name.endsWith(".c") || name.endsWith(".cc")
188                                 || name.endsWith(".cpp")) {
189                         newCode.addLine(CodeGeneratorUtils.Comment("Add the"
190                                         + SpecNaming.CDSSpecGeneratedHeader + " header file"));
191                         newCode.addLine(CodeGeneratorUtils
192                                         .IncludeHeader(SpecNaming.CDSSpecGeneratedHeader));
193                         newCode.addLine("");
194                 }
195
196                 try {
197                         br = new BufferedReader(new FileReader(file));
198                         lineReader = new LineNumberReader(br);
199                         while ((curLine = lineReader.readLine()) != null) {
200                                 lineNum = lineReader.getLineNumber();
201                                 InterfaceConstruct construct = null;
202                                 if ((construct = renamedLinesMap.get(lineNum)) != null) {
203                                         // Rename line
204                                         String newLine = construct.getFunctionHeader()
205                                                         .getRenamedFuncLine();
206                                         newCode.addLine(newLine);
207                                 } else {
208                                         // First add the current line
209                                         newCode.addLine(curLine);
210                                         // Then check if we need to add code
211                                         if (curAddition != null
212                                                         && lineNum == curAddition.insertingLine) {
213                                                 // Need to insert code
214                                                 newCode.addLines(curAddition.code);
215                                                 // Increase to the next code addition
216                                                 additionIdx++;
217                                                 curAddition = additionIdx == additions.codeAdditions
218                                                                 .size() ? null : additions.codeAdditions
219                                                                 .get(additionIdx);
220                                         }
221                                 }
222                         }
223                         // Write new code change to destination
224                         CodeGeneratorUtils.write2File(dest, newCode.lines);
225                         // System.out.println("/*************** " + file.getName()
226                         // + "  *************/");
227                         // System.out.println(newCode);
228                 } catch (FileNotFoundException e) {
229                         e.printStackTrace();
230                 } catch (IOException e) {
231                         e.printStackTrace();
232                 }
233         }
234
235         /**
236          * <p>
237          * This function is the main interface for the CodeGenerator class. After
238          * constructing a CodeGenerator object, users can call this function to
239          * complete the code generation and file writing process.
240          * </p>
241          */
242         public void generateCode() {
243                 // Extract all the code additions and line change
244                 getAllCodeChanges();
245
246                 // Generate the header file and CPP file
247                 Code generatedHeader = CodeGeneratorUtils
248                                 .GenerateCDSSpecHeaderFile(extractor);
249                 Code generatedCPP = CodeGeneratorUtils
250                                 .GenerateCDSSpecCPPFile(extractor);
251                 CodeGeneratorUtils
252                                 .write2File(generatedDir + SpecNaming.CDSSpecGeneratedName
253                                                 + ".h", generatedHeader.lines);
254                 CodeGeneratorUtils.write2File(generatedDir
255                                 + SpecNaming.CDSSpecGeneratedCPP, generatedCPP.lines);
256
257                 // Iterate over each file
258                 for (int i = 0; i < files.size(); i++) {
259                         File file = files.get(i);
260                         CodeAdditions additions = allAdditions.get(i);
261                         HashMap<Integer, InterfaceConstruct> renamedLinesMap = renamedLinesMapList
262                                         .get(i);
263                         writeCodeChange(file, additions, renamedLinesMap);
264                 }
265         }
266
267         /**
268          * <p>
269          * This is just a testing function that outputs the generated code, but not
270          * actually write them to the disk.
271          * </p>
272          */
273         private void testGenerator() {
274                 // Test code generation
275                 Code generatedHeader = CodeGeneratorUtils
276                                 .GenerateCDSSpecHeaderFile(extractor);
277                 Code generatedCPP = CodeGeneratorUtils
278                                 .GenerateCDSSpecCPPFile(extractor);
279
280                 System.out.println("/***** Generated header file *****/");
281                 System.out.println(generatedHeader);
282                 System.out.println("/***** Generated cpp file *****/");
283                 System.out.println(generatedCPP);
284
285                 for (File file : extractor.OPListMap.keySet()) {
286                         ArrayList<OPConstruct> list = extractor.OPListMap.get(file);
287                         for (OPConstruct con : list) {
288                                 Code code = CodeGeneratorUtils.Generate4OPConstruct(con);
289                                 System.out.println("/*****  *****/");
290                                 System.out.println(con.annotation);
291                                 System.out.println(code);
292                         }
293                 }
294
295                 for (File f : extractor.entryMap.keySet()) {
296                         EntryConstruct con = extractor.entryMap.get(f);
297                         System.out.println("/*****  *****/");
298                         System.out.println(con.annotation);
299                         System.out.println(CodeGeneratorUtils.Generate4Entry(con));
300                 }
301
302                 for (File file : extractor.interfaceListMap.keySet()) {
303                         ArrayList<InterfaceConstruct> list = extractor.interfaceListMap
304                                         .get(file);
305                         for (InterfaceConstruct con : list) {
306                                 Code code = CodeGeneratorUtils.GenerateInterfaceWrapper(con);
307                                 System.out.println("/***** Interface wrapper *****/");
308                                 System.out.println(con.getFunctionHeader().getHeaderLine());
309                                 System.out
310                                                 .println(con.getFunctionHeader().getRenamedFuncLine());
311                                 System.out.println(code);
312                         }
313                 }
314         }
315
316         public ArrayList<File> getSrcFiles(String dirName)
317                         throws FileNotFoundException {
318                 ArrayList<File> res = new ArrayList<File>();
319                 File dir = new File(dirName);
320                 if (dir.isDirectory() && dir.exists()) {
321                         for (String file : dir.list()) {
322                                 if (file.endsWith(".h") || file.endsWith(".c")
323                                                 || file.endsWith(".cc") || file.endsWith(".cpp")) {
324                                         res.add(new File(dir.getAbsolutePath() + "/" + file));
325                                 }
326                         }
327                 } else {
328                         throw new FileNotFoundException(dirName
329                                         + " is not a valid directory!");
330                 }
331                 return res;
332         }
333
334         static public void main(String[] args) {
335                 if (args.length < 3) {
336                         System.out
337                                         .println("Usage: CodeGenerator <Benchmarks-directory> <Directory-for-generated-files> <specific-benchmark-lists...>");
338                         return;
339                 }
340                 
341                 // String[] dirNames = a        rgs;
342                 // String[] dirNames = Environment.Benchmarks;
343                 String[] dirNames = new String[args.length - 2];
344                 for (int i = 0; i < args.length - 2; i++) {
345                         dirNames[i] = args[i + 2];
346                 }
347
348                 for (int i = 0; i < dirNames.length; i++) {
349                         String dirName = dirNames[i];
350                         System.out.println("/**********   Generating CDSSpec files for "
351                                         + dirName + "    **********/");
352                         CodeGenerator generator = new CodeGenerator(args[0], args[1], dirName);
353                         generator.generateCode();
354                 }
355         }
356 }