comparison modules/parser.tp @ 208:a1b4a2bc8d72

Initial work on pattern match macrosfor the new parser
author Mike Pavone <pavone@retrodev.com>
date Fri, 22 Nov 2013 19:37:25 -0800
parents
children 4b3b57f39f10
comparison
equal deleted inserted replaced
207:60eff5f81d9a 208:a1b4a2bc8d72
1 #{
2 expandClass <- :chars {
3 if: (chars length) > 0 {
4 pos <- 0
5 inverted <- false
6 if: (chars byte: 0) = ("^" byte: 0) {
7 pos <- 1
8 inverted <- true
9 }
10 state_begin <- 0
11 state_normal <- 1
12 state_rangeend <- 2
13 state <- state_begin
14 out <- ""
15 while: { pos < (chars byte_length)} do: {
16 if: state = state_begin {
17 out <- out . (chars from: pos withLength: 1)
18 state <- state_normal
19 } else: {
20 if: state = state_normal {
21 if: (chars byte: pos) = ("-" byte: 0) {
22 state <- state_rangeend
23 } else: {
24 out <- out . (chars from: pos withLength: 1)
25 }
26 } else: {
27 rangestart <- out byte: ((out byte_length) - 1)
28 rangeend <- chars byte: pos
29 if: rangeend < rangestart {
30 tmp <- rangeend
31 rangeend <- rangestart
32 rangestart <- tmp
33 }
34 out <- out from: 0 withLength: ((out length) - 1)
35 while: { rangestart <= rangeend } do: {
36 out <- out . (rangestart asStringChar)
37 rangestart <- rangestart + 1
38 }
39 state <- state_begin
40 }
41 }
42 pos <- pos + 1
43 }
44 if: inverted {
45 old <- out
46 out <- ""
47 cur <- 0
48 while: { cur < 256 } do: {
49 out <- out . (cur asStringChar)
50 cur <- cur + 1
51 }
52 }
53 out
54 } else: {
55 ""
56 }
57 }
58 charClass <- macro: :rawchars {
59 eval: rawchars :chars {
60 chars <- expandClass: chars
61 //TODO: Use a more sophisticated approach for large classes
62 quote: :tomatch {
63 if: (tomatch isString?) {
64 check <- 0
65
66 nomatch <- true
67 while: { nomatch && check < (chars byte_length) } do: {
68 if: (tomatch byte: 0) = (chars byte: check) {
69 nomatch <- false
70 }
71 check <- check + 1
72 }
73 if: nomatch {
74 #{
75 matched? <- { false }
76 }
77 } else: {
78 #{
79 matched? <- { true }
80 matchlen <- { 1 }
81 }
82 }
83 } else: {
84 #{
85 matched? <- { false }
86 }
87 }
88 }
89 } else: {
90 print: "uh oh"
91 }
92 }
93 alpha <- charClass: "a-zA-Z"
94
95 main <- {
96 cmatch <- alpha: "c0123"
97 zeromatch <- alpha: "01234"
98 if: (cmatch matched?) {
99 print: "c0123 matched with length " . (cmatch matchlen) . "\n"
100 } else: {
101 print: "c0123 didn't match\n"
102 }
103 if: (zeromatch matched?) {
104 print: "0123 matched with length " . (zeromatch matchlen) . "\n"
105 } else: {
106 print: "0123 didn't match\n"
107 }
108 }
109 }