fork download
  1. package net.egork.chelper.util;
  2.  
  3. import com.intellij.openapi.application.ApplicationManager;
  4. import com.intellij.openapi.fileEditor.FileEditorManager;
  5. import com.intellij.openapi.project.Project;
  6. import com.intellij.openapi.vfs.VirtualFile;
  7. import com.intellij.psi.*;
  8. import com.intellij.psi.search.searches.ReferencesSearch;
  9. import net.egork.chelper.task.*;
  10.  
  11. import javax.swing.*;
  12. import java.util.*;
  13.  
  14. /**
  15.  * @author Egor Kulikov (kulikov@devexperts.com)
  16.  */
  17. public class CodeGenerationUtilities {
  18. private static final String[] classStarts = {"class ", "abstract class", "interface ", "enum "};
  19.  
  20. public static String[] createInlinedSource(Project project, Set<String> mandatoryImports, PsiFile originalSource)
  21. {
  22. InlineVisitor inlineVisitor = new InlineVisitor(project, originalSource);
  23. List<PsiClass> toInline = inlineVisitor.toInline;
  24. Set<String> toImport = inlineVisitor.toImport;
  25. toImport.addAll(mandatoryImports);
  26. StringBuilder importsBuilder = new StringBuilder();
  27. for (String aImport : toImport) {
  28. if (!aImport.startsWith("import java.lang."))
  29. importsBuilder.append(aImport).append("\n");
  30. }
  31. importsBuilder.append("\n");
  32. importsBuilder.append("/**\n");
  33. importsBuilder.append(" * Built using CHelper plug-in\n");
  34. importsBuilder.append(" * Actual solution is at the top\n");
  35. String author = Utilities.getData(project).author;
  36. if (author.length() != 0)
  37. importsBuilder.append(" * @author ").append(author).append("\n");
  38. importsBuilder.append(" */\n");
  39. String imports = importsBuilder.toString();
  40. final StringBuilder text = new StringBuilder();
  41. for (PsiClass aClass : toInline) {
  42. String classText = aClass.getText();
  43. int startIndex = -1;
  44. for (String start : classStarts) {
  45. int index = classText.indexOf(start);
  46. if (index != -1 && (startIndex == -1 || startIndex > index))
  47. startIndex = index;
  48. }
  49. if (startIndex == -1)
  50. continue;
  51. text.append(classText.substring(startIndex));
  52. text.append("\n\n");
  53. }
  54. return new String[]{imports, text.toString()};
  55. }
  56.  
  57. public static void removeUnusedCode(final Project project, final VirtualFile virtualFile, final String mainClass,
  58. final String mainMethod)
  59. {
  60. PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
  61. if (file == null)
  62. return;
  63. PsiDirectory parent = file.getParent();
  64. PsiPackage aPackage = parent == null ? null : JavaDirectoryService.getInstance().getPackage(parent);
  65. if (aPackage == null || aPackage.getName() != null) {
  66. JOptionPane.showMessageDialog(null, "outputDirectory should be under source and in default package");
  67. return;
  68. }
  69. while (true) {
  70. final List<PsiElement> toRemove = new ArrayList<PsiElement>();
  71. file.acceptChildren(new PsiElementVisitor() {
  72. private boolean visitElementImpl(PsiElement element) {
  73. if (element instanceof PsiMethod)
  74. toRemove.addAll(Arrays.asList(((PsiMethod) element).getModifierList().getAnnotations()));
  75. if (!(element instanceof PsiClass) && !(element instanceof PsiMethod) && !(element instanceof PsiField))
  76. return true;
  77. if (element instanceof PsiMethod && ((PsiMethod) element).findSuperMethods().length != 0)
  78. return false;
  79. if (element instanceof PsiMethod && ((PsiMethod) element).isConstructor())
  80. return false;
  81. if (element instanceof PsiAnonymousClass)
  82. return false;
  83. if (element instanceof PsiMethod && mainMethod.equals(((PsiMethod) element).getName())) {
  84. PsiElement parent = element.getParent();
  85. if (parent instanceof PsiClass && mainClass.equals(((PsiClass) parent).getQualifiedName()))
  86. return false;
  87. }
  88. if (element instanceof PsiClass && mainClass.equals(((PsiClass) element).getQualifiedName()))
  89. return true;
  90. for (PsiReference reference : ReferencesSearch.search(element)) {
  91. PsiElement referenceElement = reference.getElement();
  92. while (referenceElement != null && referenceElement != element)
  93. referenceElement = referenceElement.getParent();
  94. if (referenceElement == null)
  95. return element instanceof PsiClass;
  96. }
  97. toRemove.add(element);
  98. return false;
  99. }
  100.  
  101. @Override
  102. public void visitElement(PsiElement element) {
  103. if (visitElementImpl(element))
  104. element.acceptChildren(this);
  105. }
  106. });
  107. if (toRemove.isEmpty())
  108. break;
  109. for (PsiElement element : toRemove) {
  110. if (element.isValid())
  111. element.delete();
  112. }
  113. }
  114. FileUtilities.synchronizeFile(virtualFile);
  115. }
  116.  
  117. public static String createMainClass(Task task)
  118. {
  119. StringBuilder builder = new StringBuilder();
  120. builder.append("public class Main {\n");
  121. builder.append("\tpublic static void main(String[] args) {\n");
  122. builder.append("\t\tnew Thread(null, new Runnable() {\n");
  123. builder.append("\t\t\t@Override\n");
  124. builder.append("\t\t\tpublic void run(){\n");
  125. if (task.input.type == StreamConfiguration.StreamType.STANDARD)
  126. builder.append("\t\t\t\tInputStream inputStream = System.in;\n");
  127. else {
  128. builder.append("\t\t\t\tInputStream inputStream;\n");
  129. builder.append("\t\t\t\ttry {\n");
  130. builder.append("\t\t\t\t\tinputStream = new FileInputStream(\"").append(task.input.
  131. getFileName(task.name, ".in")).append("\");\n");
  132. builder.append("\t\t\t\t} catch (IOException e) {\n");
  133. builder.append("\t\t\t\t\tthrow new RuntimeException(e);\n");
  134. builder.append("\t\t\t\t}\n");
  135. }
  136. if (task.output.type == StreamConfiguration.StreamType.STANDARD)
  137. builder.append("\t\t\t\tOutputStream outputStream = System.out;\n");
  138. else {
  139. builder.append("\t\t\t\tOutputStream outputStream;\n");
  140. builder.append("\t\t\t\ttry {\n");
  141. builder.append("\t\t\t\t\toutputStream = new FileOutputStream(\"").append(task.output.getFileName(task.name,
  142. ".out")).append("\");\n");
  143. builder.append("\t\t\t\t} catch (IOException e) {\n");
  144. builder.append("\t\t\t\t\tthrow new RuntimeException(e);\n");
  145. builder.append("\t\t\t\t}\n");
  146. }
  147. String inputClass = Utilities.getData(task.project).inputClass;
  148. String inputClassShort = inputClass.substring(inputClass.lastIndexOf('.') + 1);
  149. builder.append("\t\t\t\t").append(inputClassShort).append(" in = new ").append(inputClassShort).
  150. append("(inputStream);\n");
  151. String outputClass = Utilities.getData(task.project).outputClass;
  152. String outputClassShort = outputClass.substring(outputClass.lastIndexOf('.') + 1);
  153. builder.append("\t\t\t\t").append(outputClassShort).append(" out = new ").append(outputClassShort).
  154. append("(outputStream);\n");
  155. builder.append("\t\t\t\t").append(task.name).append(" solver = new ").append(task.name).append("();\n");
  156. switch (task.testType) {
  157. case SINGLE:
  158. builder.append("\t\t\t\tsolver.solve(1, in, out);\n");
  159. builder.append("\t\t\t\tout.close();\n");
  160. break;
  161. case MULTI_EOF:
  162. builder.append("\t\t\t\ttry {\n");
  163. builder.append("\t\t\t\t\tint testNumber = 1;\n");
  164. builder.append("\t\t\t\t\twhile (true)\n");
  165. builder.append("\t\t\t\t\t\tsolver.solve(testNumber++, in, out);\n");
  166. builder.append("\t\t\t\t} catch (UnknownError e) {\n");
  167. builder.append("\t\t\t\t\tout.close();\n");
  168. builder.append("\t\t\t\t}\n");
  169. break;
  170. case MULTI_NUMBER:
  171. builder.append("\t\t\t\tint testCount = Integer.parseInt(in.next());\n");
  172. builder.append("\t\t\t\tfor (int i = 1; i <= testCount; i++)\n");
  173. builder.append("\t\t\t\t\tsolver.solve(i, in, out);\n");
  174. builder.append("\t\t\t\tout.close();\n");
  175. break;
  176. }
  177. builder.append("\t\t\t}\n");
  178. builder.append("\t\t}, \"").append(task.name).append("\", ").append(stackSize(task.stackMemory)).append(").start();\n");
  179. builder.append("\t}\n");
  180. builder.append("}\n\n");
  181. return builder.toString();
  182. }
  183. private static int stackSize(String stackSize){
  184. try {
  185. Map<String, Integer> suffixes = new HashMap<String, Integer>();
  186. suffixes.put("G", 1<<30);
  187. suffixes.put("M", 1<<20);
  188. suffixes.put("K", 1<<10);
  189. suffixes.put("B", 1);
  190. for(Map.Entry<String, Integer> entry: suffixes.entrySet())
  191. if(stackSize.endsWith(entry.getKey()) || stackSize.endsWith(entry.getKey().toLowerCase()))
  192. return entry.getValue() * Integer.parseInt(stackSize.substring(0, stackSize.length() - entry.getKey().length()));
  193. return Integer.parseInt(stackSize);
  194. }
  195. return 1<<26;
  196. }
  197. }
  198.  
  199. public static void createSourceFile(final Task task) {
  200. ApplicationManager.getApplication().runWriteAction(new Runnable() {
  201. public void run() {
  202. Set<String> toImport = new HashSet<String>();
  203. toImport.add("import java.io.InputStream;");
  204. toImport.add("import java.io.OutputStream;");
  205. toImport.add("import java.io.IOException;");
  206. if (task.input.type != StreamConfiguration.StreamType.STANDARD)
  207. toImport.add("import java.io.FileInputStream;");
  208. if (task.output.type != StreamConfiguration.StreamType.STANDARD)
  209. toImport.add("import java.io.FileOutputStream;");
  210. PsiFile originalSource = FileUtilities.getPsiFile(task.project, task.location + "/" + task.name + ".java");
  211. final String[] textParts = createInlinedSource(task.project, toImport, originalSource);
  212. final StringBuilder text = new StringBuilder();
  213. text.append(textParts[0]);
  214. text.append(createMainClass(task));
  215. text.append(textParts[1]);
  216. String outputDirectory = Utilities.getData(task.project).outputDirectory;
  217. VirtualFile directory = FileUtilities.createDirectoryIfMissing(task.project, outputDirectory);
  218. if (directory == null)
  219. return;
  220. final VirtualFile file = FileUtilities.writeTextFile(directory, "Main.java", text.toString());
  221. FileUtilities.synchronizeFile(file);
  222. removeUnusedCode(task.project, file, "Main", "main");
  223. }
  224. });
  225. }
  226.  
  227. public static String createCheckerStub(Task task) {
  228. PsiDirectory directory = FileUtilities.getPsiDirectory(task.project, task.location);
  229. String inputClass = Utilities.getData(task.project).inputClass;
  230. String inputClassShort = inputClass.substring(inputClass.lastIndexOf('.') + 1);
  231. StringBuilder builder = new StringBuilder();
  232. String packageName = FileUtilities.getPackage(directory);
  233. if (packageName != null && packageName.length() != 0)
  234. builder.append("package ").append(packageName).append(";\n\n");
  235. builder.append("import ").append(inputClass).append(";\n");
  236. builder.append("import net.egork.chelper.task.Test;\n");
  237. builder.append("import net.egork.chelper.tester.Verdict;\n");
  238. builder.append("\n");
  239. builder.append("import java.util.Collection;\n");
  240. builder.append("import java.util.Collections;\n");
  241. builder.append("\n");
  242. builder.append("public class ").append(task.name).append("Checker {\n");
  243. builder.append("\tpublic Verdict check(").append(inputClassShort).append(" input, ").append(inputClassShort)
  244. .append(" expected, ").append(inputClassShort).append(" actual) {\n");
  245. builder.append("\t\treturn Verdict.UNDECIDED;\n");
  246. builder.append("\t}\n");
  247. builder.append("\n");
  248. builder.append("\tpublic double getCertainty() {\n");
  249. builder.append("\t\treturn 0;\n");
  250. builder.append("\t}\n");
  251. builder.append("\n");
  252. builder.append("\tpublic Collection<? extends Test> generateTests() {\n");
  253. builder.append("\t\treturn Collections.emptyList();\n");
  254. builder.append("\t}\n");
  255. builder.append("}\n");
  256. return builder.toString();
  257. }
  258.  
  259. public static String createStub(Task task) {
  260. PsiDirectory directory = FileUtilities.getPsiDirectory(task.project, task.location);
  261. String inputClass = Utilities.getData(task.project).inputClass;
  262. String inputClassShort = inputClass.substring(inputClass.lastIndexOf('.') + 1);
  263. String outputClass = Utilities.getData(task.project).outputClass;
  264. String outputClassShort = outputClass.substring(outputClass.lastIndexOf('.') + 1);
  265. StringBuilder builder = new StringBuilder();
  266. String packageName = FileUtilities.getPackage(directory);
  267. if (packageName != null && packageName.length() != 0)
  268. builder.append("package ").append(packageName).append(";\n\n");
  269. builder.append("import ").append(inputClass).append(";\n");
  270. builder.append("import ").append(outputClass).append(";\n");
  271. builder.append("\n");
  272. builder.append("public class ").append(task.name).append(" {\n");
  273. builder.append("\tpublic void solve(int testNumber, ").append(inputClassShort).append(" in, ").
  274. append(outputClassShort).append(" out) {\n");
  275. builder.append("\t}\n");
  276. builder.append("}\n");
  277. return builder.toString();
  278. }
  279.  
  280. public static TopCoderTask parseTopCoderStub(VirtualFile file, final Project project) {
  281. String text = FileUtilities.readTextFile(file);
  282. if (text == null)
  283. return null;
  284. String originalText = text;
  285. final String name = file.getNameWithoutExtension();
  286. String classSignature = "public class " + name;
  287. int index = text.indexOf(classSignature);
  288. if (index == -1)
  289. return null;
  290. text = text.substring(index + classSignature.length());
  291. int openBracketIndex = text.indexOf("{");
  292. if (openBracketIndex == -1)
  293. return null;
  294. text = text.substring(openBracketIndex + 1);
  295. int methodSignatureEnd = text.indexOf("{");
  296. if (methodSignatureEnd == -1)
  297. return null;
  298. String signatureText = text.substring(0, methodSignatureEnd).trim();
  299. MethodSignature methodSignature = MethodSignature.parse(signatureText);
  300. String testStart = "switch";
  301. int testStartIndex = text.indexOf(testStart);
  302. if (testStartIndex == -1)
  303. return null;
  304. text = text.substring(testStartIndex + testStart.length());
  305. String testEnd = "// custom cases";
  306. int testEndIndex = text.indexOf(testEnd);
  307. if (testEndIndex == -1)
  308. return null;
  309. text = text.substring(0, testEndIndex);
  310. List<TopCoderTest> tests = new ArrayList<TopCoderTest>();
  311. for (int i = 0; ; i++) {
  312. String nextTestStart = "case " + i;
  313. int nextTestStartIndex = text.indexOf(nextTestStart);
  314. if (nextTestStartIndex == -1)
  315. break;
  316. text = text.substring(nextTestStartIndex);
  317. String[] argumentsAndResult = new String[methodSignature.arguments.length + 1];
  318. for (int j = 0; j < argumentsAndResult.length; j++) {
  319. int equalsIndex = text.indexOf('=');
  320. if (equalsIndex == -1)
  321. return null;
  322. text = text.substring(equalsIndex + 1);
  323. int lineEnd = text.indexOf(";\n");
  324. if (lineEnd == -1)
  325. lineEnd = text.indexOf(";\r\n");
  326. if (lineEnd == -1)
  327. return null;
  328. argumentsAndResult[j] = text.substring(0, lineEnd).trim();
  329. Class aClass = j < argumentsAndResult.length - 1 ? methodSignature.arguments[j] : methodSignature.result;
  330. argumentsAndResult[j] = MethodSignature.toString(aClass,
  331. MethodSignature.resolve(aClass, argumentsAndResult[j]));
  332. text = text.substring(lineEnd);
  333. }
  334. tests.add(new TopCoderTest(Arrays.copyOf(argumentsAndResult, argumentsAndResult.length - 1),
  335. argumentsAndResult[argumentsAndResult.length - 1], i));
  336. }
  337. String tailStart = "// BEGIN CUT HERE";
  338. int tailIndex = originalText.indexOf(tailStart);
  339. if (tailIndex == -1)
  340. return null;
  341. originalText = originalText.substring(0, tailIndex) + "}\n\n";
  342. final String finalOriginalText = originalText;
  343. ApplicationManager.getApplication().runWriteAction(new Runnable() {
  344. public void run() {
  345. String defaultDir = Utilities.getData(project).defaultDir;
  346. FileUtilities.createDirectoryIfMissing(project, defaultDir);
  347. String packageName = FileUtilities.getPackage(FileUtilities.getPsiDirectory(project, defaultDir));
  348. if (packageName != null && packageName.length() != 0) {
  349. FileUtilities.writeTextFile(FileUtilities.getFile(project, defaultDir),
  350. name + ".java", "package " + packageName + ";\n\n" + finalOriginalText);
  351. } else {
  352. FileUtilities.writeTextFile(FileUtilities.getFile(project, defaultDir),
  353. name + ".java", finalOriginalText);
  354. }
  355. }
  356. });
  357. FileEditorManager.getInstance(project).openFile(FileUtilities.getFile(project,
  358. Utilities.getData(project).defaultDir + "/" + name + ".java"), true);
  359. return new TopCoderTask(project, name, methodSignature, tests.toArray(new TopCoderTest[tests.size()]));
  360. }
  361.  
  362. public static void createSourceFile(final TopCoderTask task) {
  363. ApplicationManager.getApplication().runWriteAction(new Runnable() {
  364. public void run() {
  365. PsiFile originalSource = FileUtilities.getPsiFile(task.project,
  366. Utilities.getData(task.project).defaultDir + "/" + task.name + ".java");
  367. String[] textParts = createInlinedSource(task.project, Collections.<String>emptySet(),
  368. originalSource);
  369. final StringBuilder text = new StringBuilder();
  370. text.append(textParts[0]);
  371. text.append("public ");
  372. text.append(textParts[1]);
  373. String outputDirectory = Utilities.getData(task.project).topcoderDir;
  374. VirtualFile directory = FileUtilities.createDirectoryIfMissing(task.project, outputDirectory);
  375. if (directory == null)
  376. return;
  377. final VirtualFile file = FileUtilities.writeTextFile(directory, task.name + ".java", text.toString());
  378. FileUtilities.synchronizeFile(file);
  379. removeUnusedCode(task.project, file, task.name, task.signature.name);
  380. }
  381. });
  382. }
  383.  
  384. public static void createUnitTest(Task task) {
  385. if (!Utilities.getData(task.project).enableUnitTests)
  386. return;
  387. Test[] tests = task.tests;
  388. for (int i = 0, testsLength = tests.length; i < testsLength; i++)
  389. tests[i] = tests[i].setActive(true);
  390. Calendar calendar = Calendar.getInstance();
  391. int year = calendar.get(Calendar.YEAR);
  392. int month = calendar.get(Calendar.MONTH);
  393. int day = calendar.get(Calendar.DAY_OF_MONTH);
  394. String path = Utilities.getData(task.project).testDir + "/on" + year + "_" + month + "_" + day + "/" +
  395. task.name.toLowerCase();
  396. String originalPath = path;
  397. int index = 0;
  398. while (FileUtilities.getFile(task.project, path) != null)
  399. path = originalPath + (index++);
  400. VirtualFile directory = FileUtilities.createDirectoryIfMissing(task.project, path);
  401. String packageName = FileUtilities.getPackage(FileUtilities.getPsiDirectory(task.project, path));
  402. if (packageName == null) {
  403. JOptionPane.showMessageDialog(null, "testDirectory should be under project source");
  404. return;
  405. }
  406. String sourceFile = FileUtilities.readTextFile(FileUtilities.getFile(task.project,
  407. task.location + "/" + task.name + ".java"));
  408. sourceFile = changePackage(sourceFile, packageName);
  409. String checkerFile = FileUtilities.readTextFile(FileUtilities.getFile(task.project,
  410. task.location + "/" + task.name + "Checker.java"));
  411. checkerFile = changePackage(checkerFile, packageName);
  412. FileUtilities.writeTextFile(directory, task.name + ".java", sourceFile);
  413. FileUtilities.writeTextFile(directory, task.name + "Checker.java", checkerFile);
  414. String tester = generateTester(task, path);
  415. tester = changePackage(tester, packageName);
  416. FileUtilities.writeTextFile(directory, "Main.java", tester);
  417. }
  418.  
  419. public static void createUnitTest(TopCoderTask task) {
  420. if (!Utilities.getData(task.project).enableUnitTests)
  421. return;
  422. TopCoderTest[] tests = task.tests;
  423. for (int i = 0, testsLength = tests.length; i < testsLength; i++)
  424. tests[i] = tests[i].setActive(true);
  425. Calendar calendar = Calendar.getInstance();
  426. int year = calendar.get(Calendar.YEAR);
  427. int month = calendar.get(Calendar.MONTH);
  428. int day = calendar.get(Calendar.DAY_OF_MONTH);
  429. String path = Utilities.getData(task.project).testDir + "/on" + year + "_" + month + "_" + day + "/" +
  430. task.name.toLowerCase();
  431. String originalPath = path;
  432. int index = 0;
  433. while (FileUtilities.getFile(task.project, path) != null)
  434. path = originalPath + (index++);
  435. VirtualFile directory = FileUtilities.createDirectoryIfMissing(task.project, path);
  436. String packageName = FileUtilities.getPackage(FileUtilities.getPsiDirectory(task.project, path));
  437. if (packageName == null) {
  438. JOptionPane.showMessageDialog(null, "testDirectory should be under project source");
  439. return;
  440. }
  441. String sourceFile = FileUtilities.readTextFile(FileUtilities.getFile(task.project,
  442. Utilities.getData(task.project).defaultDir + "/" + task.name + ".java"));
  443. sourceFile = changePackage(sourceFile, packageName);
  444. FileUtilities.writeTextFile(directory, task.name + ".java", sourceFile);
  445. String tester = generateTester(task, path);
  446. tester = changePackage(tester, packageName);
  447. FileUtilities.writeTextFile(directory, "Main.java", tester);
  448. }
  449.  
  450. private static String generateTester(Task task, String path) {
  451. StringBuilder builder = new StringBuilder();
  452. builder.append("import net.egork.chelper.tester.Tester;\n");
  453. builder.append("import org.junit.Assert;\n");
  454. builder.append("import org.junit.Test;\n\n");
  455. builder.append("public class Main {\n");
  456. builder.append("\t@Test\n");
  457. builder.append("\tpublic void test() throws Exception {\n");
  458. builder.append("\t\tif (!Tester.test(\"").append(Utilities.getData(task.project).inputClass).append("\",\n");
  459. builder.append("\t\t\t\"")
  460. .append(FileUtilities.getFQN(FileUtilities.getPsiDirectory(task.project, path), task.name))
  461. .append("\",\n");
  462. builder.append("\t\t\t\"").append(task.testType.name()).append("\",\n");
  463. builder.append("\t\t\t\"").append(escape(EncodingUtilities.encodeTests(task.tests))).append("\",\n");
  464. builder.append("\t\t\t\"").append(Utilities.getData(task.project).outputClass).append("\"))\n");
  465. builder.append("\t\t{\n");
  466. builder.append("\t\t\tAssert.fail();\n");
  467. builder.append("\t\t}\n");
  468. builder.append("\t}\n");
  469. builder.append("}\n");
  470. return builder.toString();
  471. }
  472.  
  473. private static String generateTester(TopCoderTask task, String path) {
  474. StringBuilder builder = new StringBuilder();
  475. builder.append("import net.egork.chelper.tester.TopCoderTester;\n");
  476. builder.append("import org.junit.Assert;\n");
  477. builder.append("import org.junit.Test;\n\n");
  478. builder.append("public class Main {\n");
  479. builder.append("\t@Test\n");
  480. builder.append("\tpublic void test() throws Exception {\n");
  481. builder.append("\t\tif (!TopCoderTester.test(\"").append(task.signature).append("\",\n");
  482. builder.append("\t\t\t\"")
  483. .append(FileUtilities.getFQN(FileUtilities.getPsiDirectory(task.project, path), task.name))
  484. .append("\",\n");
  485. builder.append("\t\t\t\"").append(escape(EncodingUtilities.encodeTests(task.tests))).append("\"))\n");
  486. builder.append("\t\t{\n");
  487. builder.append("\t\t\tAssert.fail();\n");
  488. builder.append("\t\t}\n");
  489. builder.append("\t}\n");
  490. builder.append("}\n");
  491. return builder.toString();
  492. }
  493.  
  494. private static String escape(String s) {
  495. StringBuilder builder = new StringBuilder();
  496. for (int i = 0; i < s.length(); i++) {
  497. char c = s.charAt(i);
  498. if (c == '"')
  499. builder.append("\\\"");
  500. else if (c == '\\')
  501. builder.append("\\\\");
  502. else
  503. builder.append(c);
  504. }
  505. return builder.toString();
  506. }
  507.  
  508. private static String changePackage(String sourceFile, String packageName) {
  509. if (sourceFile.startsWith("package ")) {
  510. int index = sourceFile.indexOf(';');
  511. if (index == -1)
  512. return sourceFile;
  513. sourceFile = sourceFile.substring(index + 1);
  514. }
  515. if (packageName.length() == 0)
  516. return sourceFile;
  517. sourceFile = "package " + packageName + ";\n\n" + sourceFile;
  518. return sourceFile;
  519. }
  520.  
  521. public static class InlineVisitor extends PsiElementVisitor {
  522. private final String[] excluded;
  523. private final HashSet<PsiClass> set;
  524. public final List<PsiClass> toInline;
  525. public final Set<String> toImport;
  526. private final Project project;
  527.  
  528. private InlineVisitor(Project project, PsiFile originalSource) {
  529. this.project = project;
  530. excluded = Utilities.getData(project).excludedPackages;
  531. toImport = new HashSet<String>();
  532. toInline = new ArrayList<PsiClass>();
  533. for (PsiElement element : originalSource.getChildren()) {
  534. if (element instanceof PsiClass)
  535. toInline.add((PsiClass)element);
  536. }
  537. set = new HashSet<PsiClass>(toInline);
  538. //noinspection ForLoopReplaceableByForEach
  539. for (int i = 0; i < toInline.size(); i++) {
  540. PsiClass aClass = toInline.get(i);
  541. processClass(aClass);
  542. aClass.acceptChildren(this);
  543. }
  544. }
  545.  
  546. private void processClass(PsiClass aClass) {
  547. PsiClass superClass = aClass.getSuperClass();
  548. addClass(superClass);
  549. PsiClass[] interfaces = aClass.getInterfaces();
  550. for (PsiClass aInterface : interfaces)
  551. addClass(aInterface);
  552. }
  553.  
  554. private void addClass(PsiClass aClass) {
  555. if (!(aClass.getScope() instanceof PsiFile))
  556. return;
  557. if (!shouldSkip(aClass)) {
  558. if (!set.contains(aClass)) {
  559. set.add(aClass);
  560. toInline.add(aClass);
  561. }
  562. } else {
  563. PsiImportStatement aImport = JavaPsiFacade.getElementFactory(project).createImportStatement(aClass);
  564. toImport.add(aImport.getText());
  565. }
  566. }
  567.  
  568. @Override
  569. public void visitElement(PsiElement element) {
  570. if (element instanceof PsiClass) {
  571. processClass((PsiClass) element);
  572. } else if (element instanceof PsiVariable) {
  573. PsiType type = ((PsiVariable) element).getType();
  574. processType(type);
  575. } else if (element instanceof PsiMethod) {
  576. processMethod((PsiMethod) element);
  577. } else if (element instanceof PsiMethodCallExpression) {
  578. PsiMethod method = ((PsiMethodCallExpression) element).resolveMethod();
  579. if (method != null) {
  580. addClass(method.getContainingClass());
  581. processMethod(method);
  582. }
  583. } else if (element instanceof PsiNewExpression) {
  584. processType(((PsiNewExpression) element).getType());
  585. } else if (element instanceof PsiReferenceExpression) {
  586. PsiElement resolved = ((PsiReferenceExpression) element).resolve();
  587. if (resolved instanceof PsiClass)
  588. addClass((PsiClass) resolved);
  589. }
  590. element.acceptChildren(this);
  591. }
  592.  
  593. private void processMethod(PsiMethod element) {
  594. processType(element.getReturnType());
  595. for (PsiParameter parameter : element.getParameterList().getParameters())
  596. processType(parameter.getType());
  597. }
  598.  
  599. private void processType(PsiType type) {
  600. while (type instanceof PsiArrayType)
  601. type = ((PsiArrayType) type).getComponentType();
  602. if (type instanceof PsiClassType)
  603. addClass(((PsiClassType) type).resolve());
  604. }
  605.  
  606. private boolean shouldSkip(PsiClass aClass) {
  607. String fqn = aClass.getQualifiedName();
  608. if (fqn == null)
  609. return false;
  610. for (String aPackage : excluded) {
  611. if (fqn.startsWith(aPackage))
  612. return true;
  613. }
  614. return false;
  615. }
  616.  
  617. }
  618. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:17: error: class CodeGenerationUtilities is public, should be declared in a file named CodeGenerationUtilities.java
public class CodeGenerationUtilities {
       ^
Main.java:3: error: package com.intellij.openapi.application does not exist
import com.intellij.openapi.application.ApplicationManager;
                                       ^
Main.java:4: error: package com.intellij.openapi.fileEditor does not exist
import com.intellij.openapi.fileEditor.FileEditorManager;
                                      ^
Main.java:5: error: package com.intellij.openapi.project does not exist
import com.intellij.openapi.project.Project;
                                   ^
Main.java:6: error: package com.intellij.openapi.vfs does not exist
import com.intellij.openapi.vfs.VirtualFile;
                               ^
Main.java:7: error: package com.intellij.psi does not exist
import com.intellij.psi.*;
^
Main.java:8: error: package com.intellij.psi.search.searches does not exist
import com.intellij.psi.search.searches.ReferencesSearch;
                                       ^
Main.java:9: error: package net.egork.chelper.task does not exist
import net.egork.chelper.task.*;
^
Main.java:20: error: cannot find symbol
	public static String[] createInlinedSource(Project project, Set<String> mandatoryImports, PsiFile originalSource)
	                                           ^
  symbol:   class Project
  location: class CodeGenerationUtilities
Main.java:20: error: cannot find symbol
	public static String[] createInlinedSource(Project project, Set<String> mandatoryImports, PsiFile originalSource)
	                                                                                          ^
  symbol:   class PsiFile
  location: class CodeGenerationUtilities
Main.java:57: error: cannot find symbol
	public static void removeUnusedCode(final Project project, final VirtualFile virtualFile, final String mainClass,
	                                          ^
  symbol:   class Project
  location: class CodeGenerationUtilities
Main.java:57: error: cannot find symbol
	public static void removeUnusedCode(final Project project, final VirtualFile virtualFile, final String mainClass,
	                                                                 ^
  symbol:   class VirtualFile
  location: class CodeGenerationUtilities
Main.java:117: error: cannot find symbol
	public static String createMainClass(Task task)
	                                     ^
  symbol:   class Task
  location: class CodeGenerationUtilities
Main.java:200: error: cannot find symbol
	public static void createSourceFile(final Task task) {
	                                          ^
  symbol:   class Task
  location: class CodeGenerationUtilities
Main.java:228: error: cannot find symbol
	public static String createCheckerStub(Task task) {
	                                       ^
  symbol:   class Task
  location: class CodeGenerationUtilities
Main.java:260: error: cannot find symbol
	public static String createStub(Task task) {
	                                ^
  symbol:   class Task
  location: class CodeGenerationUtilities
Main.java:281: error: cannot find symbol
	public static TopCoderTask parseTopCoderStub(VirtualFile file, final Project project) {
	                                             ^
  symbol:   class VirtualFile
  location: class CodeGenerationUtilities
Main.java:281: error: cannot find symbol
	public static TopCoderTask parseTopCoderStub(VirtualFile file, final Project project) {
	                                                                     ^
  symbol:   class Project
  location: class CodeGenerationUtilities
Main.java:281: error: cannot find symbol
	public static TopCoderTask parseTopCoderStub(VirtualFile file, final Project project) {
	              ^
  symbol:   class TopCoderTask
  location: class CodeGenerationUtilities
Main.java:363: error: cannot find symbol
	public static void createSourceFile(final TopCoderTask task) {
	                                          ^
  symbol:   class TopCoderTask
  location: class CodeGenerationUtilities
Main.java:385: error: cannot find symbol
	public static void createUnitTest(Task task) {
	                                  ^
  symbol:   class Task
  location: class CodeGenerationUtilities
Main.java:420: error: cannot find symbol
	public static void createUnitTest(TopCoderTask task) {
	                                  ^
  symbol:   class TopCoderTask
  location: class CodeGenerationUtilities
Main.java:451: error: cannot find symbol
	private static String generateTester(Task task, String path) {
	                                     ^
  symbol:   class Task
  location: class CodeGenerationUtilities
Main.java:474: error: cannot find symbol
	private static String generateTester(TopCoderTask task, String path) {
	                                     ^
  symbol:   class TopCoderTask
  location: class CodeGenerationUtilities
Main.java:522: error: cannot find symbol
	public static class InlineVisitor extends PsiElementVisitor {
	                                          ^
  symbol:   class PsiElementVisitor
  location: class CodeGenerationUtilities
Main.java:524: error: cannot find symbol
		private final HashSet<PsiClass> set;
		                      ^
  symbol:   class PsiClass
  location: class InlineVisitor
Main.java:525: error: cannot find symbol
		public final List<PsiClass> toInline;
		                  ^
  symbol:   class PsiClass
  location: class InlineVisitor
Main.java:527: error: cannot find symbol
		private final Project project;
		              ^
  symbol:   class Project
  location: class InlineVisitor
Main.java:529: error: cannot find symbol
		private InlineVisitor(Project project, PsiFile originalSource) {
		                      ^
  symbol:   class Project
  location: class InlineVisitor
Main.java:529: error: cannot find symbol
		private InlineVisitor(Project project, PsiFile originalSource) {
		                                       ^
  symbol:   class PsiFile
  location: class InlineVisitor
Main.java:547: error: cannot find symbol
		private void processClass(PsiClass aClass) {
		                          ^
  symbol:   class PsiClass
  location: class InlineVisitor
Main.java:555: error: cannot find symbol
		private void addClass(PsiClass aClass) {
		                      ^
  symbol:   class PsiClass
  location: class InlineVisitor
Main.java:570: error: cannot find symbol
		public void visitElement(PsiElement element) {
		                         ^
  symbol:   class PsiElement
  location: class InlineVisitor
Main.java:594: error: cannot find symbol
		private void processMethod(PsiMethod element) {
		                           ^
  symbol:   class PsiMethod
  location: class InlineVisitor
Main.java:600: error: cannot find symbol
		private void processType(PsiType type) {
		                         ^
  symbol:   class PsiType
  location: class InlineVisitor
Main.java:607: error: cannot find symbol
		private boolean shouldSkip(PsiClass aClass) {
		                           ^
  symbol:   class PsiClass
  location: class InlineVisitor
Main.java:23: error: cannot find symbol
		List<PsiClass> toInline = inlineVisitor.toInline;
		     ^
  symbol:   class PsiClass
  location: class CodeGenerationUtilities
Main.java:35: error: cannot find symbol
		String author = Utilities.getData(project).author;
		                ^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:41: error: cannot find symbol
		for (PsiClass aClass : toInline) {
		     ^
  symbol:   class PsiClass
  location: class CodeGenerationUtilities
Main.java:60: error: cannot find symbol
		PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
		^
  symbol:   class PsiFile
  location: class CodeGenerationUtilities
Main.java:60: error: cannot find symbol
		PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
		               ^
  symbol:   variable PsiManager
  location: class CodeGenerationUtilities
Main.java:63: error: cannot find symbol
		PsiDirectory parent = file.getParent();
		^
  symbol:   class PsiDirectory
  location: class CodeGenerationUtilities
Main.java:64: error: cannot find symbol
		PsiPackage aPackage = parent == null ? null : JavaDirectoryService.getInstance().getPackage(parent);
		^
  symbol:   class PsiPackage
  location: class CodeGenerationUtilities
Main.java:64: error: cannot find symbol
		PsiPackage aPackage = parent == null ? null : JavaDirectoryService.getInstance().getPackage(parent);
		                                              ^
  symbol:   variable JavaDirectoryService
  location: class CodeGenerationUtilities
Main.java:70: error: cannot find symbol
			final List<PsiElement> toRemove = new ArrayList<PsiElement>();
			           ^
  symbol:   class PsiElement
  location: class CodeGenerationUtilities
Main.java:70: error: cannot find symbol
			final List<PsiElement> toRemove = new ArrayList<PsiElement>();
			                                                ^
  symbol:   class PsiElement
  location: class CodeGenerationUtilities
Main.java:71: error: cannot find symbol
			file.acceptChildren(new PsiElementVisitor() {
			                        ^
  symbol:   class PsiElementVisitor
  location: class CodeGenerationUtilities
Main.java:109: error: cannot find symbol
			for (PsiElement element : toRemove) {
			     ^
  symbol:   class PsiElement
  location: class CodeGenerationUtilities
Main.java:114: error: cannot find symbol
		FileUtilities.synchronizeFile(virtualFile);
		^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:125: error: package StreamConfiguration does not exist
		if (task.input.type == StreamConfiguration.StreamType.STANDARD)
		                                          ^
Main.java:136: error: package StreamConfiguration does not exist
		if (task.output.type == StreamConfiguration.StreamType.STANDARD)
		                                           ^
Main.java:147: error: cannot find symbol
		String inputClass = Utilities.getData(task.project).inputClass;
		                    ^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:151: error: cannot find symbol
		String outputClass = Utilities.getData(task.project).outputClass;
		                     ^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:157: error: cannot find symbol
		case SINGLE:
		     ^
  symbol:   variable SINGLE
  location: class CodeGenerationUtilities
Main.java:161: error: cannot find symbol
		case MULTI_EOF:
		     ^
  symbol:   variable MULTI_EOF
  location: class CodeGenerationUtilities
Main.java:170: error: cannot find symbol
		case MULTI_NUMBER:
		     ^
  symbol:   variable MULTI_NUMBER
  location: class CodeGenerationUtilities
Main.java:207: error: package StreamConfiguration does not exist
				if (task.input.type != StreamConfiguration.StreamType.STANDARD)
				                                          ^
Main.java:209: error: package StreamConfiguration does not exist
				if (task.output.type != StreamConfiguration.StreamType.STANDARD)
				                                           ^
Main.java:211: error: cannot find symbol
				PsiFile originalSource = FileUtilities.getPsiFile(task.project, task.location + "/" + task.name + ".java");
				^
  symbol: class PsiFile
Main.java:211: error: cannot find symbol
				PsiFile originalSource = FileUtilities.getPsiFile(task.project, task.location + "/" + task.name + ".java");
				                         ^
  symbol: variable FileUtilities
Main.java:217: error: cannot find symbol
				String outputDirectory = Utilities.getData(task.project).outputDirectory;
				                         ^
  symbol: variable Utilities
Main.java:218: error: cannot find symbol
				VirtualFile directory = FileUtilities.createDirectoryIfMissing(task.project, outputDirectory);
				^
  symbol: class VirtualFile
Main.java:218: error: cannot find symbol
				VirtualFile directory = FileUtilities.createDirectoryIfMissing(task.project, outputDirectory);
				                        ^
  symbol: variable FileUtilities
Main.java:221: error: cannot find symbol
				final VirtualFile file = FileUtilities.writeTextFile(directory, "Main.java", text.toString());
				      ^
  symbol: class VirtualFile
Main.java:221: error: cannot find symbol
				final VirtualFile file = FileUtilities.writeTextFile(directory, "Main.java", text.toString());
				                         ^
  symbol: variable FileUtilities
Main.java:222: error: cannot find symbol
				FileUtilities.synchronizeFile(file);
				^
  symbol: variable FileUtilities
Main.java:201: error: cannot find symbol
		ApplicationManager.getApplication().runWriteAction(new Runnable() {
		^
  symbol:   variable ApplicationManager
  location: class CodeGenerationUtilities
Main.java:229: error: cannot find symbol
		PsiDirectory directory = FileUtilities.getPsiDirectory(task.project, task.location);
		^
  symbol:   class PsiDirectory
  location: class CodeGenerationUtilities
Main.java:229: error: cannot find symbol
		PsiDirectory directory = FileUtilities.getPsiDirectory(task.project, task.location);
		                         ^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:230: error: cannot find symbol
		String inputClass = Utilities.getData(task.project).inputClass;
		                    ^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:233: error: cannot find symbol
		String packageName = FileUtilities.getPackage(directory);
		                     ^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:261: error: cannot find symbol
		PsiDirectory directory = FileUtilities.getPsiDirectory(task.project, task.location);
		^
  symbol:   class PsiDirectory
  location: class CodeGenerationUtilities
Main.java:261: error: cannot find symbol
		PsiDirectory directory = FileUtilities.getPsiDirectory(task.project, task.location);
		                         ^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:262: error: cannot find symbol
		String inputClass = Utilities.getData(task.project).inputClass;
		                    ^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:264: error: cannot find symbol
		String outputClass = Utilities.getData(task.project).outputClass;
		                     ^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:267: error: cannot find symbol
		String packageName = FileUtilities.getPackage(directory);
		                     ^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:282: error: cannot find symbol
		String text = FileUtilities.readTextFile(file);
		              ^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:300: error: cannot find symbol
		MethodSignature methodSignature = MethodSignature.parse(signatureText);
		^
  symbol:   class MethodSignature
  location: class CodeGenerationUtilities
Main.java:300: error: cannot find symbol
		MethodSignature methodSignature = MethodSignature.parse(signatureText);
		                                  ^
  symbol:   variable MethodSignature
  location: class CodeGenerationUtilities
Main.java:311: error: cannot find symbol
		List<TopCoderTest> tests = new ArrayList<TopCoderTest>();
		     ^
  symbol:   class TopCoderTest
  location: class CodeGenerationUtilities
Main.java:311: error: cannot find symbol
		List<TopCoderTest> tests = new ArrayList<TopCoderTest>();
		                                         ^
  symbol:   class TopCoderTest
  location: class CodeGenerationUtilities
Main.java:332: error: cannot find symbol
					MethodSignature.resolve(aClass, argumentsAndResult[j]));
					^
  symbol:   variable MethodSignature
  location: class CodeGenerationUtilities
Main.java:331: error: cannot find symbol
				argumentsAndResult[j] = MethodSignature.toString(aClass,
				                        ^
  symbol:   variable MethodSignature
  location: class CodeGenerationUtilities
Main.java:335: error: cannot find symbol
			tests.add(new TopCoderTest(Arrays.copyOf(argumentsAndResult, argumentsAndResult.length - 1),
			              ^
  symbol:   class TopCoderTest
  location: class CodeGenerationUtilities
Main.java:346: error: cannot find symbol
				String defaultDir = Utilities.getData(project).defaultDir;
				                    ^
  symbol: variable Utilities
Main.java:347: error: cannot find symbol
				FileUtilities.createDirectoryIfMissing(project, defaultDir);
				^
  symbol: variable FileUtilities
Main.java:348: error: cannot find symbol
				String packageName = FileUtilities.getPackage(FileUtilities.getPsiDirectory(project, defaultDir));
				                                              ^
  symbol: variable FileUtilities
Main.java:348: error: cannot find symbol
				String packageName = FileUtilities.getPackage(FileUtilities.getPsiDirectory(project, defaultDir));
				                     ^
  symbol: variable FileUtilities
Main.java:350: error: cannot find symbol
					FileUtilities.writeTextFile(FileUtilities.getFile(project, defaultDir),
					                            ^
  symbol: variable FileUtilities
Main.java:350: error: cannot find symbol
					FileUtilities.writeTextFile(FileUtilities.getFile(project, defaultDir),
					^
  symbol: variable FileUtilities
Main.java:353: error: cannot find symbol
					FileUtilities.writeTextFile(FileUtilities.getFile(project, defaultDir),
					                            ^
  symbol: variable FileUtilities
Main.java:353: error: cannot find symbol
					FileUtilities.writeTextFile(FileUtilities.getFile(project, defaultDir),
					^
  symbol: variable FileUtilities
Main.java:344: error: cannot find symbol
		ApplicationManager.getApplication().runWriteAction(new Runnable() {
		^
  symbol:   variable ApplicationManager
  location: class CodeGenerationUtilities
Main.java:359: error: cannot find symbol
			Utilities.getData(project).defaultDir + "/" + name + ".java"), true);
			^
  symbol:   variable Utilities
  location: class CodeGenerationUtilities
Main.java:358: error: cannot find symbol
		FileEditorManager.getInstance(project).openFile(FileUtilities.getFile(project,
		                                                ^
  symbol:   variable FileUtilities
  location: class CodeGenerationUtilities
Main.java:358: error: cannot find symbol
		FileEditorManager.getInstance(project).openFile(FileUtilities.getFile(project,
		^
  symbol:   variable FileEditorManager
  location: class CodeGenerationUtilities
Main.java:360: error: cannot find symbol
		return new TopCoderTask(project, name, methodSignature, tests.toArray(new TopCoderTest[tests.size()]));
		           ^
  symbol:   class TopCoderTask
  location: class CodeGenerationUtilities
Main.java:360: error: cannot find symbol
		return new TopCoderTask(project, name, methodSignature, tests.toArray(new TopCoderTest[tests.size()]));
		                                                                          ^
  symbol:   class TopCoderTest
  location: class CodeGenerationUtilities
Main.java:366: error: cannot find symbol
				PsiFile originalSource = FileUtilities.getPsiFile(task.project,
				^
  symbol: class PsiFile
Main.java:367: error: cannot find symbol
					Utilities.getData(task.project).defaultDir + "/" + task.name + ".java");
					^
  symbol: variable Utilities
100 errors
stdout
Standard output is empty