3 This file is part of libmspstrings
4 Copyright © 2007 Mikko Rasa
5 Distributed under the LGPL
10 #include <msp/core/except.h>
11 #include "formatter.h"
19 Writes an integer to a Regex code string, in little-endian order.
22 void write_int(T n, Msp::Regex::Code &code)
24 for(unsigned i=0; i<sizeof(T); ++i)
29 Reads an integer from a Regex code stream, in little-endian order.
32 T read_int(Msp::Regex::Code::const_iterator &c)
35 for(unsigned i=0; i<sizeof(T); ++i)
36 result+=static_cast<unsigned char>(*c++)<<i*8;
44 Regex::Regex(const string &expr)
47 string::const_iterator iter=expr.begin();
48 code=compile(expr, iter, n_groups, false);
52 RegMatch Regex::match(const string &str) const
54 RegMatch::GroupArray groups(n_groups);
56 for(string::const_iterator i=str.begin(); i!=str.end(); ++i)
57 if(run(str, i, groups))
58 return RegMatch(str, groups);
63 string Regex::disassemble() const
67 for(Code::const_iterator i=code.begin(); i!=code.end();)
69 Code::const_iterator j=i;
70 Offset offset=i-code.begin();
71 string decompiled=disassemble_instruction(i);
74 bytes+=format(" %02X", static_cast<int>(*j)&0xFF);
75 ss<<Fmt("%3d")<<offset<<':'<<Fmt("%-9s")<<bytes;
77 ss<<"\n"<<Fmt("%15s");
78 ss<<" "<<decompiled<<'\n';
84 Regex::Code Regex::compile(const string &expr, string::const_iterator &iter, unsigned &group, bool branch)
86 bool has_branches=false;
90 string::const_iterator end;
91 for(end=iter; end!=expr.end(); ++end)
97 if(bracket==3 && *end==']')
99 else if(bracket==1 && *end=='^')
113 throw InvalidParameterValue("Unexpected )");
119 else if(*end=='|' && level==0)
131 throw InvalidParameterValue("Unmatched (");
135 unsigned this_group=group;
139 write_int<Index>(this_group, result);
142 const unsigned jump_size=1+sizeof(Offset);
146 for(string::const_iterator i=iter; i!=end;)
148 Code atom=parse_atom(expr, i, group);
152 parse_repeat(i, repeat_min, repeat_max);
154 for(unsigned j=0; j<repeat_min; ++j)
156 if(repeat_max==numeric_limits<Count>::max())
161 write_int<Offset>(atom.size()+jump_size, result);
165 write_int<Offset>(-(atom.size()+jump_size), result);
167 else if(repeat_max>repeat_min)
169 for(unsigned j=repeat_min; j<repeat_max; ++j)
172 write_int<Offset>((repeat_max-j)*(atom.size()+jump_size)-jump_size, result);
181 for(string::const_iterator i=iter;;)
183 branches.push_back(compile(expr, i, group, true));
189 unsigned n_branches=branches.size();
191 Offset offset=(n_branches-1)*jump_size+branches.front().size();
192 for(list<Code>::iterator i=++branches.begin(); i!=branches.end(); ++i)
195 write_int<Offset>(offset, result);
199 for(list<Code>::iterator i=branches.begin(); i!=branches.end();)
202 offset-=i->size()+jump_size;
204 if(i!=branches.end())
207 write_int<Offset>(offset, result);
215 write_int<Index>(this_group, result);
223 Regex::Code Regex::parse_atom(const string &expr, string::const_iterator &i, unsigned &group)
234 throw InvalidParameterValue("Stray backslash");
240 if(*i=='*' || *i=='{' || *i=='}' || *i=='+' || *i=='?' || *i=='|' || *i==')')
241 throw InvalidParameterValue("Invalid atom");
243 return parse_brackets(expr, i);
253 result=compile(expr, ++i, group, false);
270 bool Regex::parse_repeat(string::const_iterator &i, Count &rmin, Count &rmax)
272 if(*i!='*' && *i!='+' && *i!='?' && *i!='{')
275 if(*i=='*' || *i=='+')
276 rmax=numeric_limits<Count>::max();
277 if(*i=='*' || *i=='?')
282 for(++i; isdigit(*i); ++i)
283 rmin=rmin*10+(*i-'0');
291 for(; isdigit(*i); ++i)
292 rmax=rmax*10+(*i-'0');
294 throw InvalidParameterValue("Invalid bound");
297 rmax=numeric_limits<Count>::max();
302 throw InvalidParameterValue("Invalid bound");
310 Regex::Code Regex::parse_brackets(const string &str, string::const_iterator &iter)
322 string::const_iterator end=iter;
323 for(; (end!=str.end() && (end==iter || *end!=']')); ++end) ;
325 throw InvalidParameterValue("Unmatched '['");
327 unsigned char mask[32]={0};
330 unsigned char first=0, last=0;
331 for(string::const_iterator i=iter; i!=end; ++i)
337 for(unsigned j=first; j<=c; ++j)
338 mask[j>>3]|=1<<(j&7);
343 else if(c=='-' && i!=iter && end-i>1)
348 mask[c>>3]|=1<<(c&7);
373 result.append(reinterpret_cast<char *>(mask), 32);
382 bool Regex::run(const string &str, const string::const_iterator &begin, RegMatch::GroupArray &groups) const
385 list<RunContext> ctx;
386 ctx.push_back(RunContext());
387 ctx.front().citer=code.begin();
388 ctx.front().groups.resize(groups.size());
390 for(string::const_iterator i=begin;;)
394 c=static_cast<unsigned char>(*i);
398 for(list<RunContext>::iterator j=ctx.begin(); j!=ctx.end();)
400 bool terminate=false;
401 bool negate_match=false;
402 for(; j->citer!=code.end();)
404 Instruction instr=static_cast<Instruction>(*j->citer++);
410 Offset offset=read_int<Offset>(j->citer);
413 else if(instr==ND_JUMP)
415 Offset offset=read_int<Offset>(j->citer);
417 ctx.back().citer+=offset;
419 else if(instr==GROUP_BEGIN)
421 Index n=read_int<Index>(j->citer);
422 if(!j->groups[n].match)
423 j->groups[n].begin=i-str.begin();
425 else if(instr==GROUP_END)
427 Index n=read_int<Index>(j->citer);
428 if(!j->groups[n].match)
430 j->groups[n].match=true;
431 j->groups[n].end=i-str.begin();
432 j->groups[n].length=j->groups[n].end-j->groups[n].begin;
439 for(unsigned k=0; (k<groups.size() && !better); ++k)
441 better=group_compare(j->groups[k], groups[k]);
442 if(group_compare(groups[k], j->groups[k]))
451 bool match_result=false;
452 bool input_consumed=false;
453 if(instr==MATCH_BEGIN)
454 match_result=(i==str.begin());
455 else if(instr==MATCH_END)
456 match_result=(i==str.end());
457 else if(instr==MATCH_CHAR)
459 match_result=(c==*j->citer++);
462 else if(instr==MATCH_RANGE)
464 unsigned char first=*j->citer++;
465 unsigned char last=*j->citer++;
466 match_result=(c>=first && c<=last);
469 else if(instr==MATCH_MASK)
473 unsigned char m=*(j->citer+(c>>3));
474 match_result=m&(1<<(c&7));
479 else if(instr==MATCH_ANY)
485 throw Exception("Invalid instruction");
487 if(match_result==negate_match)
491 if(input_consumed || terminate)
496 if(terminate || j->citer==code.end())
502 if(i==str.end() || ctx.empty())
510 bool Regex::group_compare(const RegMatch::Group &g1, const RegMatch::Group &g2) const
515 // Any match is better than no match
519 // Earlier match is better
520 if(g1.begin<g2.begin)
522 if(g2.begin>g2.begin)
525 // Longer match at same position is better
526 return g1.end>g2.end;
529 string Regex::disassemble_instruction(Code::const_iterator &i) const
531 Instruction instr=static_cast<Instruction>(*i++);
533 ostringstream result;
538 Offset offset=read_int<Offset>(i);
539 result<<"JUMP "<<Fmt("%+d")<<offset<<" ("<<Fmt("%d")<<i-code.begin()+offset<<')';
544 Offset offset=read_int<Offset>(i);
545 result<<"ND_JUMP "<<Fmt("%+d")<<offset<<" ("<<Fmt("%d")<<i-code.begin()+offset<<')';
549 result<<"GROUP_BEGIN "<<read_int<Index>(i);
552 result<<"GROUP_END "<<read_int<Index>(i);
558 result<<"MATCH_BEGIN";
566 result<<"MATCH_CHAR ";
567 if(c>=0x20 && c<=0x7E)
568 result<<'\''<<c<<'\'';
570 result<<(static_cast<int>(c)&0xFF);
574 result<<"MATCH_RANGE "<<(static_cast<int>(*i++)&0xFF);
575 result<<'-'<<(static_cast<int>(*i++)&0xFF);
578 result<<"MATCH_MASK";
579 for(unsigned j=0; j<32; ++j)
580 result<<' '<<Fmt("%02X")<<(static_cast<int>(*i++)&0xFF);
586 result<<"UNKNOWN "<<instr;