1 #include <msp/core/raii.h>
2 #include "glsl_error.h"
3 #include "preprocessor.h"
13 Tokenizer::Tokenizer():
14 allow_preprocess(true)
18 source_end = empty.end();
22 void Tokenizer::begin(const string &name, const string &src)
25 source_end = src.end();
28 allow_preprocess = true;
33 const string &Tokenizer::peek_token(unsigned index)
35 while(next_tokens.size()<=index)
36 next_tokens.push_back(parse_token_());
37 return (last_token = next_tokens[index]);
40 const string &Tokenizer::parse_token()
42 if(!next_tokens.empty())
44 last_token = next_tokens.front();
45 next_tokens.pop_front();
49 return (last_token = parse_token_());
52 void Tokenizer::expect(const string &token)
54 string parsed = parse_token();
56 throw parse_error(location, parsed, format("'%s'", token));
59 string Tokenizer::parse_token_()
63 skip_comment_and_whitespace();
64 bool allow_preproc = allow_preprocess;
65 allow_preprocess = false;
68 else if(allow_preproc && *iter=='#')
73 else if(isalpha(*iter) || *iter=='_')
74 return parse_identifier();
75 else if(isdigit(*iter))
76 return parse_number();
77 else if(*iter=='"' || *iter=='#' || *iter=='$' || *iter=='\'' || *iter=='@' || *iter=='\\' || *iter=='`')
78 throw syntax_error(location, string(1, *iter), "Invalid character in source");
84 void Tokenizer::preprocess()
86 SetForScope<deque<string> > clear_tokens(next_tokens, deque<string>());
88 string::const_iterator line_end = iter;
89 for(; (line_end!=source_end && *line_end!='\n'); ++line_end) ;
90 SetForScope<string::const_iterator> stop_at_line_end(source_end, line_end);
92 signal_preprocess.emit();
97 string Tokenizer::parse_identifier()
100 while(iter!=source_end)
102 if(isalnum(*iter) || *iter=='_')
111 string Tokenizer::parse_number()
113 bool got_fract = false;
115 while(iter!=source_end)
119 else if(!got_fract && *iter=='.')
128 bool require_digit = false;
129 if(iter!=source_end && (*iter=='e' || *iter=='E'))
132 if(iter!=source_end && (*iter=='-' || *iter=='+'))
134 require_digit = true;
135 while(iter!=source_end)
140 require_digit = false;
148 throw syntax_error(location, number, "Incomplete numeric literal");
149 else if(isalnum(*iter) || *iter=='_')
150 throw syntax_error(location, number, "Garbage at end of numeric literal");
155 string Tokenizer::parse_other()
160 string token(1, *iter++);
161 for(unsigned i=1; (i<3 && iter!=source_end); ++i)
163 bool matched = false;
164 for(const Operator *j=Operator::operators; (!matched && j->type); ++j)
166 matched = (j->token[i]==*iter);
167 for(unsigned k=0; (matched && k<i && j->token[k]); ++k)
168 matched = (j->token[k]==token[k]);
180 void Tokenizer::skip_comment_and_whitespace()
182 unsigned comment = 0;
183 while(iter!=source_end)
189 else if(!isspace(*iter))
210 else if(comment==3 && *iter=='*')
223 allow_preprocess = (comment<3);