3 This file is part of libmspstrings
4 Copyright © 2007 Mikko Rasa
5 Distributed under the LGPL
8 #include <msp/core/except.h>
17 Writes an integer to a Regex code string, in little-endian order.
20 void write_int(T n, Msp::Regex::Code &code)
22 for(unsigned i=0; i<sizeof(T); ++i)
27 Reads an integer from a Regex code stream, in little-endian order.
30 T read_int(Msp::Regex::Code::const_iterator &c)
33 for(unsigned i=0; i<sizeof(T); ++i)
34 result+=static_cast<unsigned char>(*c++)<<i*8;
42 Regex::Regex(const string &expr)
45 string::const_iterator iter=expr.begin();
46 code=compile(expr, iter, n_groups, false);
50 RegMatch Regex::match(const string &str) const
52 RegMatch::GroupArray groups(n_groups);
54 for(string::const_iterator i=str.begin(); i!=str.end(); ++i)
55 if(run(str, i, groups))
56 return RegMatch(str, groups);
61 string Regex::disassemble() const
65 for(Code::const_iterator i=code.begin(); i!=code.end();)
67 Code::const_iterator j=i;
68 Offset offset=i-code.begin();
69 string decompiled=disassemble_instruction(i);
72 bytes+=format(" %02X", static_cast<int>(*j)&0xFF);
73 ss<<Fmt("%3d")<<offset<<':'<<Fmt("%-9s")<<bytes;
75 ss<<"\n"<<Fmt("%15s");
76 ss<<" "<<decompiled<<'\n';
82 Regex::Code Regex::compile(const string &expr, string::const_iterator &iter, unsigned &group, bool branch)
84 bool has_branches=false;
87 string::const_iterator end;
88 for(end=iter; end!=expr.end(); ++end)
101 throw InvalidParameterValue("Unexpected )");
117 throw InvalidParameterValue("Unmatched (");
121 unsigned this_group=group;
125 write_int<Index>(this_group, result);
128 const unsigned jump_size=1+sizeof(Offset);
132 for(string::const_iterator i=iter; i!=end;)
134 Code atom=parse_atom(expr, i, group);
138 parse_repeat(i, repeat_min, repeat_max);
140 for(unsigned j=0; j<repeat_min; ++j)
142 if(repeat_max==numeric_limits<Count>::max())
147 write_int<Offset>(atom.size()+jump_size, result);
151 write_int<Offset>(-(atom.size()+jump_size), result);
153 else if(repeat_max>repeat_min)
155 for(unsigned j=repeat_min; j<repeat_max; ++j)
158 write_int<Offset>((repeat_max-j)*(atom.size()+jump_size)-jump_size, result);
167 for(string::const_iterator i=iter;;)
169 branches.push_back(compile(expr, i, group, true));
175 unsigned n_branches=branches.size();
177 Offset offset=(n_branches-1)*jump_size+branches.front().size();
178 for(list<Code>::iterator i=++branches.begin(); i!=branches.end(); ++i)
181 write_int<Offset>(offset, result);
185 for(list<Code>::iterator i=branches.begin(); i!=branches.end();)
188 offset-=i->size()+jump_size;
190 if(i!=branches.end())
193 write_int<Offset>(offset, result);
201 write_int<Index>(this_group, result);
209 Regex::Code Regex::parse_atom(const string &expr, string::const_iterator &i, unsigned &group)
220 throw InvalidParameterValue("Stray backslash");
226 if(*i=='*' || *i=='{' || *i=='}' || *i=='+' || *i=='?' || *i=='|' || *i==')')
227 throw InvalidParameterValue("Invalid atom");
229 return parse_brackets(expr, i);
239 result=compile(expr, ++i, group, false);
256 bool Regex::parse_repeat(string::const_iterator &i, Count &rmin, Count &rmax)
258 if(*i!='*' && *i!='+' && *i!='?' && *i!='{')
261 if(*i=='*' || *i=='+')
262 rmax=numeric_limits<Count>::max();
263 if(*i=='*' || *i=='?')
268 for(++i; isdigit(*i); ++i)
269 rmin=rmin*10+(*i-'0');
277 for(; isdigit(*i); ++i)
278 rmax=rmax*10+(*i-'0');
280 throw InvalidParameterValue("Invalid bound");
283 rmax=numeric_limits<Count>::max();
288 throw InvalidParameterValue("Invalid bound");
296 Regex::Code Regex::parse_brackets(const string &str, string::const_iterator &iter)
308 string::const_iterator end=iter;
309 for(; (end!=str.end() && (end==iter || *end!=']')); ++end);
311 throw InvalidParameterValue("Unmatched '['");
313 uint8_t mask[32]={0};
316 unsigned char first=0, last=0;
317 for(string::const_iterator i=iter; i!=end; ++i)
323 for(unsigned j=first; j<=c; ++j)
324 mask[j>>3]|=1<<(j&7);
329 else if(c=='-' && i!=iter && end-i>1)
334 mask[c>>3]|=1<<(c&7);
359 result.append(reinterpret_cast<char *>(mask), 32);
368 bool Regex::run(const string &str, const string::const_iterator &begin, RegMatch::GroupArray &groups) const
371 list<RunContext> ctx;
372 ctx.push_back(RunContext());
373 ctx.front().citer=code.begin();
374 ctx.front().groups.resize(groups.size());
376 for(string::const_iterator i=begin;;)
380 c=static_cast<unsigned char>(*i);
384 for(list<RunContext>::iterator j=ctx.begin(); j!=ctx.end();)
386 bool terminate=false;
387 bool negate_match=false;
388 for(; j->citer!=code.end();)
390 Instruction instr=static_cast<Instruction>(*j->citer++);
396 Offset offset=read_int<Offset>(j->citer);
399 else if(instr==ND_JUMP)
401 Offset offset=read_int<Offset>(j->citer);
403 ctx.back().citer+=offset;
405 else if(instr==GROUP_BEGIN)
407 Index n=read_int<Index>(j->citer);
408 if(!j->groups[n].match)
409 j->groups[n].begin=i-str.begin();
411 else if(instr==GROUP_END)
413 Index n=read_int<Index>(j->citer);
414 if(!j->groups[n].match)
416 j->groups[n].match=true;
417 j->groups[n].end=i-str.begin();
418 j->groups[n].length=j->groups[n].end-j->groups[n].begin;
425 for(unsigned k=0; (k<groups.size() && !better); ++k)
427 better=group_compare(j->groups[k], groups[k]);
428 if(group_compare(groups[k], j->groups[k]))
437 bool match_result=false;
438 bool input_consumed=false;
439 if(instr==MATCH_BEGIN)
440 match_result=(i==str.begin());
441 else if(instr==MATCH_END)
442 match_result=(i==str.end());
443 else if(instr==MATCH_CHAR)
445 match_result=(c==*j->citer++);
448 else if(instr==MATCH_RANGE)
450 unsigned char first=*j->citer++;
451 unsigned char last=*j->citer++;
452 match_result=(c>=first && c<=last);
455 else if(instr==MATCH_MASK)
458 for(unsigned k=0; k<32; ++k)
460 match_result=mask[c>>3]&(1<<(c&7));
463 else if(instr==MATCH_ANY)
469 throw Exception("Invalid instruction");
471 if(match_result==negate_match)
475 if(input_consumed || terminate)
480 if(terminate || j->citer==code.end())
486 if(i==str.end() || ctx.empty())
494 bool Regex::group_compare(const RegMatch::Group &g1, const RegMatch::Group &g2) const
499 // Any match is better than no match
503 // Earlier match is better
504 if(g1.begin<g2.begin)
506 if(g2.begin>g2.begin)
509 // Longer match at same position is better
510 return g1.end>g2.end;
513 string Regex::disassemble_instruction(Code::const_iterator &i) const
515 Instruction instr=static_cast<Instruction>(*i++);
517 ostringstream result;
522 Offset offset=read_int<Offset>(i);
523 result<<"JUMP "<<Fmt("%+d")<<offset<<" ("<<Fmt("%d")<<i-code.begin()+offset<<')';
528 Offset offset=read_int<Offset>(i);
529 result<<"ND_JUMP "<<Fmt("%+d")<<offset<<" ("<<Fmt("%d")<<i-code.begin()+offset<<')';
533 result<<"GROUP_BEGIN "<<read_int<Index>(i);
536 result<<"GROUP_END "<<read_int<Index>(i);
542 result<<"MATCH_BEGIN";
550 result<<"MATCH_CHAR ";
551 if(c>=0x20 && c<=0x7E)
552 result<<'\''<<c<<'\'';
554 result<<(static_cast<int>(c)&0xFF);
558 result<<"MATCH_RANGE "<<(static_cast<int>(*i++)&0xFF);
559 result<<'-'<<(static_cast<int>(*i++)&0xFF);
562 result<<"MATCH_MASK";
563 for(unsigned j=0; j<32; ++j)
564 result<<' '<<Fmt("%02X")<<(static_cast<int>(*i++)&0xFF);
570 result<<"UNKNOWN "<<instr;