Debian Codegraph @

src/main/java/com/eprosima/idl/test/TestIDLParser.java

raw
1 package com.eprosima.idl.test;
2
3
4 import java.io.BufferedReader;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.io.OutputStream;
11 import java.lang.reflect.AnnotatedElement;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.Collection;
15
16 import org.antlr.v4.runtime.CharStream;
17 import org.antlr.v4.runtime.CharStreams;
18 import org.antlr.v4.runtime.CommonTokenStream;
19
20
21 import com.eprosima.idl.context.Context;
22 import com.eprosima.idl.generator.manager.TemplateManager;
23 import com.eprosima.idl.parser.grammar.IDLLexer;
24 import com.eprosima.idl.parser.grammar.IDLParser;
25 import com.eprosima.idl.parser.tree.Annotation;
26 import com.eprosima.idl.parser.tree.AnnotationDeclaration;
27 import com.eprosima.idl.parser.tree.AnnotationMember;
28 import com.eprosima.idl.parser.tree.ConstDeclaration;
29 import com.eprosima.idl.parser.tree.Definition;
30 import com.eprosima.idl.parser.tree.Interface;
31 import com.eprosima.idl.parser.tree.Module;
32 import com.eprosima.idl.parser.tree.Specification;
33 import com.eprosima.idl.parser.tree.TypeDeclaration;
34 import com.eprosima.idl.parser.typecode.*;
35 import com.eprosima.idl.util.Util;
36 import com.eprosima.log.ColorMessage;
37
38
39 public class TestIDLParser {
40
41 private String m_tempDir = null;
42 private String m_os = null;
43 private String m_ppPath = null;
44 private ArrayList<String> m_includePaths = new ArrayList<String>();
45
46 public TestIDLParser() {
47 m_os = System.getProperty("os.name");
48 }
49
50 public void addIncludePath(String path)
51 {
52 m_includePaths.add("-I" + path);
53 }
54
55 public void setPreprocessorPath(String path)
56 {
57 m_ppPath = path;
58 }
59
60 public void setTemporalPath(String path)
61 {
62 m_tempDir = path;
63 }
64
65 public void parse(String idlFileName) {
66
67 System.out.println("Start Parsing IDL File: " + idlFileName + "\n");
68
69 //m_includePaths.add("-Ie:\\data\\idl");
70
71 String idlParseFileName = callPreprocessor(idlFileName);
72
73 if (idlParseFileName == null)
74 {
75 System.out.println("Error calling preprocessor.");
76 return;
77 }
78
79 TemplateManager tmanager = new TemplateManager();
80 Context context = new Context(tmanager, idlFileName, m_includePaths, false);
81
82 try {
83
84 CharStream input = CharStreams.fromFileName(idlParseFileName);
85 IDLLexer lexer = new IDLLexer(input);
86 lexer.setContext(context);
87 CommonTokenStream tokenStream = new CommonTokenStream(lexer);
88 IDLParser parser = new IDLParser(tokenStream);
89 Specification specification = parser.specification(context, null, null).spec;
90
91 if (specification != null)
92 {
93 for( Definition definition: specification.getDefinitions()) {
94
95 if (definition.isIsModule())
96 {
97 parseModule((Module)definition);
98 }
99 else if (definition.isIsInterface())
100 {
101 parseInterface((Interface)definition);
102 }
103 else if (definition.isIsException())
104 {
105 parseException((com.eprosima.idl.parser.tree.Exception)definition);
106 }
107 else if (definition.isIsTypeDeclaration())
108 {
109 parseTypeDeclaration((TypeDeclaration)definition);
110 }
111 else if (definition.isIsConstDeclaration())
112 {
113 parseConstDeclaration((ConstDeclaration)definition);
114 }
115 else if (definition.isIsAnnotation())
116 {
117 parseAnnotation((AnnotationDeclaration)definition);
118 }
119 else
120 {
121 System.out.println("Unknown Type");
122 }
123 }
124 }
125
126 } catch (IOException e) {
127 e.printStackTrace();
128 }
129 System.out.println("\nParsing Completed \n");
130
131 }
132
133 public void parseModule(Module moduleDef) {
134 System.out.println("Start Module: " + moduleDef.getName() + "\n");
135
136 for( Definition moduleDefinition: moduleDef.getDefinitions())
137 {
138 if (moduleDefinition.isIsTypeDeclaration())
139 {
140 parseTypeDeclaration((TypeDeclaration) moduleDefinition);
141 }
142 else if (moduleDefinition.isIsInterface())
143 {
144 parseInterface((Interface)moduleDefinition);
145 }
146 else if (moduleDefinition.isIsModule())
147 {
148 parseModule((Module)moduleDefinition);
149 }
150 else if (moduleDefinition.isIsException())
151 {
152 parseException((com.eprosima.idl.parser.tree.Exception)moduleDefinition);
153 }
154 else if (moduleDefinition.isIsConstDeclaration())
155 {
156 parseConstDeclaration((ConstDeclaration)moduleDefinition);
157 }
158 else if (moduleDefinition.isIsAnnotation())
159 {
160 parseAnnotation((AnnotationDeclaration)moduleDefinition);
161 }
162 else
163 {
164 System.out.println("Module Unrecognized Option ");
165 }
166 }
167 System.out.println("End Module: " + moduleDef.getName());
168 }
169
170 public void parseInterface(Interface interfaceDef) {
171 System.out.println("Start Interface: " + interfaceDef.getName());
172 System.out.println("End Interface: \n");
173 }
174
175 public void parseException(com.eprosima.idl.parser.tree.Exception exceptionDef)
176 {
177 System.out.println("Start Exception: " + exceptionDef.getName());
178 System.out.println("End Annotation: \n");
179 }
180
181 public void parseAnnotations(Collection<Annotation> annotations, boolean new_line, String tab)
182 {
183 for (Annotation annotation : annotations)
184 {
185 System.out.print(tab + "@" + annotation.getName());
186 if (annotation.getValues().size() > 0)
187 {
188 boolean first = true;
189 System.out.print(" (");
190 for (AnnotationMember member : annotation.getValues().values())
191 {
192 if (!first)
193 {
194 System.out.print(", ");
195 }
196 System.out.print(member.getName() + " = " + member.getValue());
197 first = false;
198 }
199 if (new_line) System.out.println(")");
200 else System.out.print(") ");
201 }
202 }
203 }
204
205 public void parseTypeDeclaration(TypeDeclaration typeDeclarationDef)
206 {
207 if (typeDeclarationDef.getAnnotations().size() > 0)
208 {
209 parseAnnotations(typeDeclarationDef.getAnnotations().values(), true , "");
210 }
211 switch (typeDeclarationDef.getTypeCode().getKind()) {
212 case Kind.KIND_STRUCT:
213 parseStruct((StructTypeCode)typeDeclarationDef.getTypeCode());
214 break;
215 case Kind.KIND_UNION:
216 parseUnion((UnionTypeCode)typeDeclarationDef.getTypeCode());
217 break;
218 case Kind.KIND_ENUM:
219 parseEnum((EnumTypeCode)typeDeclarationDef.getTypeCode());
220 break;
221 case Kind.KIND_ALIAS:
222 parseAlias((AliasTypeCode)typeDeclarationDef.getTypeCode());
223 break;
224 case Kind.KIND_BITSET:
225 parseBitset((BitsetTypeCode)typeDeclarationDef.getTypeCode());
226 break;
227 case Kind.KIND_BITMASK:
228 parseBitmask((BitmaskTypeCode)typeDeclarationDef.getTypeCode());
229 break;
230 default:
231 System.out.println("Parse Type Declaration: Not Handled ");
232 }
233 }
234
235 public void parseConstDeclaration(ConstDeclaration constDeclarationDef)
236 {
237 System.out.println("Start ConstDeclaration: " + constDeclarationDef.getName());
238 System.out.println(" - Type: " + constDeclarationDef.getTypeCode().getTypeIdentifier());
239 System.out.println(" - Value: " + constDeclarationDef.getValue());
240 System.out.println("End Annotation: \n");
241 }
242
243 public void parseAnnotation(AnnotationDeclaration annotationDef) {
244 System.out.println("Start Annotation: " + annotationDef.getName());
245 for (AnnotationMember member : annotationDef.getMembers())
246 {
247 System.out.println(" " + member.getTypecode().getTypeIdentifier() + " " + member.getName());
248 }
249 System.out.println("End Annotation: \n");
250 }
251
252 public void parseAlias(AliasTypeCode aliasType) {
253 System.out.println("Start Alias (TypeDef) ");
254 System.out.println("End Alias: \n");
255 }
256
257 public void parseMember(Member member)
258 {
259 if (member.getAnnotations().size() > 0)
260 {
261 parseAnnotations(member.getAnnotations().values(), false, " ");
262 }
263
264 if (member.getTypecode() instanceof EnumTypeCode){
265 parseEnumField(member);
266 } else if (member.getTypecode() instanceof StructTypeCode){
267 parseStructField(member);
268 } else if (member.getTypecode() instanceof UnionTypeCode){
269 parseUnionField(member);
270 } else if (member.getTypecode() instanceof AliasTypeCode) {
271 parseAliasField(member);
272 } else if (member.getTypecode() instanceof PrimitiveTypeCode) {
273 parsePrimitiveField(member);
274 } else if (member.getTypecode() instanceof BitsetTypeCode) {
275 parseBitsetField(member);
276 } else if (member.getTypecode() instanceof BitmaskTypeCode) {
277 parseBitmaskField(member);
278 } else {
279 parseDefaultField(member);
280 }
281 }
282
283 public void parseUnionMember(UnionMember member)
284 {
285 for (String label : member.getLabels())
286 {
287 System.out.print(" " + label + " - ");
288 }
289 if (member.isDefault())
290 {
291 System.out.print(" Default - ");
292 }
293
294 if (member.getAnnotations().size() > 0)
295 {
296 parseAnnotations(member.getAnnotations().values(), false, " ");
297 }
298
299 if (member.getTypecode() instanceof EnumTypeCode){
300 parseEnumField(member);
301 } else if (member.getTypecode() instanceof StructTypeCode){
302 parseStructField(member);
303 } else if (member.getTypecode() instanceof UnionTypeCode){
304 parseUnionField(member);
305 } else if (member.getTypecode() instanceof AliasTypeCode) {
306 parseAliasField(member);
307 } else if (member.getTypecode() instanceof PrimitiveTypeCode) {
308 parsePrimitiveField(member);
309 } else if (member.getTypecode() instanceof BitsetTypeCode) {
310 parseBitsetField(member);
311 } else if (member.getTypecode() instanceof BitmaskTypeCode) {
312 parseBitmaskField(member);
313 } else {
314 parseDefaultField(member);
315 }
316 }
317
318 public void parseStruct(StructTypeCode struct) {
319 System.out.println("Start Struct: " + struct.getName());
320 for (Member member: struct.getMembers(true)) {
321 parseMember(member);
322 }
323 System.out.println("End Struct: \n");
324 }
325
326 public void parseUnion(UnionTypeCode union) {
327 System.out.println("Start Union: " + union.getName() + " (" + union.getDiscriminator().getTypecode().getTypeIdentifier() + ")");
328 for (Member member: union.getMembers()) {
329 parseUnionMember((UnionMember)member);
330 }
331 System.out.println("End Union: \n");
332 }
333
334 public void parseBitset(BitsetTypeCode bitset) {
335 System.out.println("Start Bitset: " + bitset.getName());
336 for (Bitfield field : bitset.getBitfields()) {
337 parseBitfield(field);
338 }
339 System.out.println("End Bitset: \n");
340 }
341
342 public void parseBitmask(BitmaskTypeCode bitmask) {
343 System.out.println("Start Bitmask: " + bitmask.getName() + " (" + bitmask.getBitBound() + ")");
344 for (Bitmask mask : bitmask.getBitmasks()) {
345 parseBitmask(mask);
346 }
347 System.out.println("End Bitset: \n");
348 }
349
350 public static void parseBitfield(Bitfield field) {
351 System.out.println(" Bitfield: " + field.getName() + " (" + field.getSpec().getBitSize() + ")" );
352 }
353
354 public static void parseBitmask(Bitmask mask) {
355 System.out.println(" Bitmask: " + mask.getName() + " (" + mask.getPosition() + ")" );
356 }
357
358 public static void parsePrimitiveField(Member member) {
359 System.out.println(" Field " + member.getTypecode().getTypeIdentifier() + ": " + member.getName() );
360 }
361
362 public static void parseDefaultField(Member member) {
363 System.out.println(" Field " + member.getTypecode().getStType() + ": " + member.getName() );
364 }
365
366 public static void parseBitsetField(Member member) {
367 System.out.println(" Field bitset: " + member.getName() );
368 }
369
370 public static void parseBitmaskField(Member member) {
371 System.out.println(" Field bitmask: " + member.getName() );
372 }
373
374 public void parseEnum(EnumTypeCode enumType) {
375 System.out.println("Enum: " + enumType.getName());
376 for (Member member: enumType.getMembers()) {
377 System.out.println(" Enum Member: " + member.getName());
378 }
379 System.out.println("End Enum: \n");
380 }
381
382 // Fields Parse
383 public void parseEnumField(Member member) {
384 EnumTypeCode typeCode = (EnumTypeCode) member.getTypecode();
385 System.out.println(" Field Enum: " + typeCode.getName() + " " + member.getName());
386 }
387
388 public void parseStructField(Member member) {
389 StructTypeCode typeCode = (StructTypeCode) member.getTypecode();
390 System.out.println(" Field Struct: " + typeCode.getName() + " " + member.getName());
391 }
392
393 public void parseUnionField(Member member) {
394 UnionTypeCode typeCode = (UnionTypeCode) member.getTypecode();
395 System.out.println(" Field Union: " + typeCode.getName() + " " + member.getName());
396 }
397
398 public void parseAliasField(Member member) {
399 AliasTypeCode typeCode = (AliasTypeCode)member.getTypecode();
400 System.out.println(" Field Alias: " + typeCode.getName() + " " + member.getName() );
401 }
402
403
404 String callPreprocessor(String idlFilename)
405 {
406 final String METHOD_NAME = "callPreprocessor";
407
408 // Set line command.
409 ArrayList<String> lineCommand = new ArrayList<String>();
410 String [] lineCommandArray = null;
411 String outputfile = Util.getIDLFileOnly(idlFilename) + ".cc";
412 int exitVal = -1;
413 OutputStream of = null;
414
415 // Use temp directory.
416 if (m_tempDir != null) {
417 outputfile = m_tempDir + outputfile;
418 }
419
420 if (m_os.contains("Windows")) {
421 try {
422 of = new FileOutputStream(outputfile);
423 } catch (FileNotFoundException ex) {
424 System.out.println(ColorMessage.error(METHOD_NAME) + "Cannot open file " + outputfile);
425 return null;
426 }
427 }
428
429 // Set the preprocessor path
430 String ppPath = m_ppPath;
431
432 if (ppPath == null) {
433 if (m_os.contains("Windows")) {
434 // the path for the cl.exe should be configured as required
435 ppPath = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.12.25827\\bin\\Hostx64\\x64\\cl.exe";
436 } else if (m_os.contains("Linux") || m_os.contains("Mac")) {
437 ppPath = "cpp";
438 }
439 }
440
441 // Add command
442 lineCommand.add(ppPath);
443
444 // Add the include paths given as parameters.
445 for (int i=0; i < m_includePaths.size(); ++i) {
446 if (m_os.contains("Windows")) {
447 lineCommand.add(((String) m_includePaths.get(i)).replaceFirst("^-I", "/I"));
448 } else if (m_os.contains("Linux") || m_os.contains("Mac")) {
449 lineCommand.add(m_includePaths.get(i));
450 }
451 }
452
453 if (m_os.contains("Windows")) {
454 lineCommand.add("/E");
455 lineCommand.add("/C");
456 }
457
458 // Add input file.
459 lineCommand.add(idlFilename);
460
461 if(m_os.contains("Linux") || m_os.contains("Mac")) {
462 lineCommand.add(outputfile);
463 }
464
465 lineCommandArray = new String[lineCommand.size()];
466 lineCommandArray = (String[])lineCommand.toArray(lineCommandArray);
467
468 try {
469 Process preprocessor = Runtime.getRuntime().exec(lineCommandArray);
470 ProcessOutput errorOutput = new ProcessOutput(preprocessor.getErrorStream(), "ERROR", false, null, true);
471 ProcessOutput normalOutput = new ProcessOutput(preprocessor.getInputStream(), "OUTPUT", false, of, true);
472 errorOutput.start();
473 normalOutput.start();
474 exitVal = preprocessor.waitFor();
475 errorOutput.join();
476 normalOutput.join();
477 } catch (Exception e) {
478 System.out.println(ColorMessage.error(METHOD_NAME) + "Cannot execute the preprocessor. Reason: " + e.getMessage());
479 return null;
480 }
481
482 if (of != null) {
483 try {
484 of.close();
485 } catch (IOException e) {
486 System.out.println(ColorMessage.error(METHOD_NAME) + "Cannot close file " + outputfile);
487 }
488
489 }
490
491 if (exitVal != 0) {
492 System.out.println(ColorMessage.error(METHOD_NAME) + "Preprocessor return an error " + exitVal);
493 return null;
494 }
495
496 return outputfile;
497 }
498
499
500 class ProcessOutput extends Thread
501 {
502 InputStream is = null;
503 OutputStream of = null;
504 String type;
505 boolean m_check_failures;
506 boolean m_found_error = false;
507 final String clLine = "#line";
508 boolean m_printLine = false;
509
510 ProcessOutput(InputStream is, String type, boolean check_failures, OutputStream of, boolean printLine)
511 {
512 this.is = is;
513 this.type = type;
514 m_check_failures = check_failures;
515 this.of = of;
516 m_printLine = printLine;
517 }
518
519 public void run()
520 {
521 try
522 {
523 InputStreamReader isr = new InputStreamReader(is);
524 BufferedReader br = new BufferedReader(isr);
525 String line=null;
526 while ( (line = br.readLine()) != null)
527 {
528 if(of == null)
529 {
530 if(m_printLine)
531 System.out.println(line);
532 }
533 else
534 {
535 // Sustituir los \\ que pone cl.exe por \
536 if(line.startsWith(clLine))
537 {
538 line = "#" + line.substring(clLine.length());
539 int count = 0;
540 while((count = line.indexOf("\\\\")) != -1)
541 {
542 line = line.substring(0, count) + "\\" + line.substring(count + 2);
543 }
544 }
545
546 of.write(line.getBytes());
547 of.write('\n');
548 }
549
550 if(m_check_failures)
551 {
552 if(line.startsWith("Done (failures)"))
553 {
554 m_found_error = true;
555 }
556 }
557 }
558 }
559 catch (IOException ioe)
560 {
561 ioe.printStackTrace();
562 }
563 }
564
565 boolean getFoundError()
566 {
567 return m_found_error;
568 }
569 }
570
571
572 //
573 // Main for test
574 //
575 public static void main(String[] args)
576 {
577 TestIDLParser parser = new TestIDLParser();
578
579 HashMap<String, ArrayList<String>> argsList = new HashMap<String, ArrayList<String>>();
580 String currentOption = "f";
581 argsList.put(currentOption, new ArrayList<String>());
582 ArrayList<String> current_list = argsList.get(currentOption);
583 for (int i = 0; i < args.length; ++i)
584 {
585 switch(args[i].charAt(0))
586 {
587 case '-':
588 {
589 if (args[i].length() == 2)
590 {
591 switch(args[i].charAt(1))
592 {
593 case 'I': // Include
594 currentOption = "I";
595 break;
596 case 't': // Temporal path
597 currentOption = "t";
598 break;
599 case 'p': // Preprocessor path
600 currentOption = "p";
601 break;
602 default:
603 System.out.println("ERROR: Unknown option: " + args[i]);
604 usage();
605 return;
606 }
607 if (argsList.containsKey(currentOption))
608 {
609 System.out.println("ERROR: Option: previously defined: " + args[i]);
610 usage();
611 return;
612 }
613 else
614 {
615 current_list = new ArrayList<String>();
616 argsList.put(currentOption, current_list);
617 }
618 }
619 else
620 {
621 System.out.println("ERROR: Unknown option: " + args[i]);
622 usage();
623 return;
624 }
625 }
626 default:
627 current_list.add(args[i]);
628 break;
629 }
630 }
631
632 if (argsList.containsKey("t"))
633 {
634 parser.setTemporalPath(argsList.get("t").get(0));
635 }
636
637 if (argsList.containsKey("p"))
638 {
639 parser.setPreprocessorPath(argsList.get("p").get(0));
640 }
641
642 if (argsList.containsKey("I"))
643 {
644 for (String p : argsList.get("I"))
645 {
646 parser.addIncludePath(p);
647 }
648 }
649
650 if (argsList.containsKey("f") && argsList.get("f").size() > 0)
651 {
652 for (String f : argsList.get("f"))
653 {
654 parser.parse(f);
655 }
656 }
657 else
658 {
659 System.out.println("ERROR: No input files.");
660 usage();
661 }
662 }
663
664 public static void usage()
665 {
666 System.out.println("Usage:");
667 System.out.println("idlparser <file>+ [-I <include_path>+] [-t <temporal_path>] [-p <preprocessor_path>]");
668 }
669
670 }