* Big cleanups.
[oota-llvm.git] / lib / AsmParser / Parser.cpp
1 //===- Parser.cpp - Main dispatch module for the Parser library -------------===
2 //
3 // This library implements the functionality defined in llvm/assembly/parser.h
4 //
5 //===------------------------------------------------------------------------===
6
7 #include "llvm/Analysis/Verifier.h"
8 #include "llvm/Module.h"
9 #include "ParserInternals.h"
10 #include <stdio.h>  // for sprintf
11 using std::string;
12
13 // The useful interface defined by this file... Parse an ascii file, and return
14 // the internal representation in a nice slice'n'dice'able representation.
15 //
16 Module *ParseAssemblyFile(const string &Filename) { // throw (ParseException)
17   FILE *F = stdin;
18
19   if (Filename != "-") 
20     F = fopen(Filename.c_str(), "r");
21
22   if (F == 0) {
23     throw ParseException(Filename, string("Could not open file '") + 
24                          Filename + "'");
25   }
26
27   // TODO: If this throws an exception, F is not closed.
28   Module *Result = RunVMAsmParser(Filename, F);
29
30   if (F != stdin)
31     fclose(F);
32
33   if (Result) {  // Check to see that it is valid...
34     std::vector<string> Errors;
35     if (verify(Result, Errors)) {
36       delete Result; Result = 0;
37       string Message;
38
39       for (unsigned i = 0; i < Errors.size(); i++)
40         Message += Errors[i] + "\n";
41
42       throw ParseException(Filename, Message);
43     }
44   }
45   return Result;
46 }
47
48
49 //===------------------------------------------------------------------------===
50 //                              ParseException Class
51 //===------------------------------------------------------------------------===
52
53
54 ParseException::ParseException(const string &filename, const string &message, 
55                                int lineNo, int colNo) 
56   : Filename(filename), Message(message) {
57   LineNo = lineNo; ColumnNo = colNo;
58 }
59
60 ParseException::ParseException(const ParseException &E) 
61   : Filename(E.Filename), Message(E.Message) {
62   LineNo = E.LineNo;
63   ColumnNo = E.ColumnNo;
64 }
65
66 const string ParseException::getMessage() const { // Includes info from options
67   string Result;
68   char Buffer[10];
69
70   if (Filename == "-") 
71     Result += "<stdin>";
72   else
73     Result += Filename;
74
75   if (LineNo != -1) {
76     sprintf(Buffer, "%d", LineNo);
77     Result += string(":") + Buffer;
78     if (ColumnNo != -1) {
79       sprintf(Buffer, "%d", ColumnNo);
80       Result += string(",") + Buffer;
81     }
82   }
83   
84   return Result + ": " + Message;
85 }