Rewrite of core coder & decoder functions to fix several bugs and limitations, and...
[mono.git] / mcs / class / Microsoft.Build.Engine / Microsoft.Build.BuildEngine / ConditionParser.cs
1 //
2 // ConditionParser.cs
3 //
4 // Author:
5 //   Marek Sieradzki (marek.sieradzki@gmail.com)
6 //   Jaroslaw Kowalski <jaak@jkowalski.net>
7 // 
8 // (C) 2006 Marek Sieradzki
9 // (C) 2004-2006 Jaroslaw Kowalski
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 //
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 //
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29
30 using System;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Text;
34
35 namespace Microsoft.Build.BuildEngine {
36
37         internal class ConditionParser {
38         
39                 ConditionTokenizer tokenizer;
40                 string conditionStr;
41                 
42                 ConditionParser (string condition)
43                 {
44                         tokenizer = new ConditionTokenizer ();
45                         tokenizer.Tokenize (condition);
46                         conditionStr = condition;
47                 }
48                 
49                 public static bool ParseAndEvaluate (string condition, Project context)
50                 {
51                         if (String.IsNullOrEmpty (condition))
52                                 return true;
53
54                         try {
55                                 ConditionExpression ce = ParseCondition (condition);
56
57                                 if (!ce.CanEvaluateToBool (context))
58                                         throw new InvalidProjectFileException (String.Format ("Can not evaluate \"{0}\" to bool.", condition));
59
60                                 return ce.BoolEvaluate (context);
61                         } catch (ExpressionParseException epe) {
62                                 throw new InvalidProjectFileException (
63                                                 String.Format ("Unable to parse condition \"{0}\" : {1}", condition, epe.Message),
64                                                 epe);
65                         } catch (ExpressionEvaluationException epe) {
66                                 throw new InvalidProjectFileException (
67                                                 String.Format ("Unable to evaluate condition \"{0}\" : {1}", condition, epe.Message),
68                                                 epe);
69                         }
70                 }
71
72                 public static ConditionExpression ParseCondition (string condition)
73                 {
74                         ConditionParser parser = new ConditionParser (condition);
75                         ConditionExpression e = parser.ParseExpression ();
76                         
77                         if (!parser.tokenizer.IsEOF ())
78                                 throw new ExpressionParseException (String.Format ("Unexpected token found, {0}, in condition \"{1}\"", parser.tokenizer.Token, condition));
79                         
80                         return e;
81                 }
82                 
83                 ConditionExpression ParseExpression ()
84                 {
85                         return ParseBooleanExpression ();
86                 }
87                 
88                 ConditionExpression ParseBooleanExpression ()
89                 {
90                         return ParseBooleanAnd ();
91                 }
92                 
93                 ConditionExpression ParseBooleanAnd ()
94                 {
95                         ConditionExpression e = ParseBooleanOr ();
96                         
97                         while (tokenizer.IsToken (TokenType.And)) {
98                                 tokenizer.GetNextToken ();
99                                 e = new ConditionAndExpression (e, ParseBooleanOr ());
100                         }
101                         
102                         return e;
103                 }
104                 
105                 ConditionExpression ParseBooleanOr ()
106                 {
107                         ConditionExpression e = ParseRelationalExpression ();
108                         
109                         while (tokenizer.IsToken (TokenType.Or)) {
110                                 tokenizer.GetNextToken ();
111                                 e = new ConditionOrExpression (e, ParseRelationalExpression ());
112                         }
113                         
114                         return e;
115                 }
116                 
117                 ConditionExpression ParseRelationalExpression ()
118                 {
119                         ConditionExpression e = ParseFactorExpression ();
120                         
121                         Token opToken;
122                         RelationOperator op;
123                         
124                         if (tokenizer.IsToken (TokenType.Less) ||
125                                 tokenizer.IsToken (TokenType.Greater) ||
126                                 tokenizer.IsToken (TokenType.Equal) ||
127                                 tokenizer.IsToken (TokenType.NotEqual) ||
128                                 tokenizer.IsToken (TokenType.LessOrEqual) ||
129                                 tokenizer.IsToken (TokenType.GreaterOrEqual)) {
130                                 
131                                 opToken = tokenizer.Token;
132                                 tokenizer.GetNextToken ();
133                                                                 
134                                 switch (opToken.Type) {
135                                 case TokenType.Equal:
136                                         op = RelationOperator.Equal;
137                                         break;
138                                 case TokenType.NotEqual:
139                                         op = RelationOperator.NotEqual;
140                                         break;
141                                 case TokenType.Less:
142                                         op = RelationOperator.Less;
143                                         break;
144                                 case TokenType.LessOrEqual:
145                                         op = RelationOperator.LessOrEqual;
146                                         break;
147                                 case TokenType.Greater:
148                                         op = RelationOperator.Greater;
149                                         break;
150                                 case TokenType.GreaterOrEqual:
151                                         op = RelationOperator.GreaterOrEqual;
152                                         break;
153                                 default:
154                                         throw new ExpressionParseException (String.Format ("Wrong relation operator {0}", opToken.Value));
155                                 }
156
157                                 e =  new ConditionRelationalExpression (e, ParseFactorExpression (), op);
158                         }
159                         
160                         return e;
161                 }
162                 
163                 ConditionExpression ParseFactorExpression ()
164                 {
165                         ConditionExpression e;
166                         Token token = tokenizer.Token;
167                         tokenizer.GetNextToken ();
168
169                         if (token.Type == TokenType.LeftParen) {
170                                 e = ParseExpression ();
171                                 tokenizer.Expect (TokenType.RightParen);
172                         } else if (token.Type == TokenType.String && tokenizer.Token.Type == TokenType.LeftParen) {
173                                 e = ParseFunctionExpression (token.Value);
174                         } else if (token.Type == TokenType.String) {
175                                 e = new ConditionFactorExpression (token);
176                         } else if (token.Type == TokenType.Number) {
177                                 e = new ConditionFactorExpression (token);
178                         } else if (token.Type == TokenType.Item || token.Type == TokenType.Property
179                                         || token.Type == TokenType.Metadata) {
180                                 e = ParseReferenceExpression (token.Value);
181                         } else if (token.Type == TokenType.Not) {
182                                 e = ParseNotExpression ();
183                         } else
184                                 throw new ExpressionParseException (String.Format ("Unexpected token {0}, while parsing condition \"{1}\"", token, conditionStr));
185                         
186                         return e;
187                 }
188
189                 ConditionExpression ParseNotExpression ()
190                 {
191                         return new ConditionNotExpression (ParseFactorExpression ());
192                 }
193
194                 ConditionExpression ParseFunctionExpression (string function_name)
195                 {
196                         return new ConditionFunctionExpression (function_name, ParseFunctionArguments ());
197                 }
198                 
199                 List <ConditionFactorExpression> ParseFunctionArguments ()
200                 {
201                         List <ConditionFactorExpression> list = new List <ConditionFactorExpression> ();
202                         ConditionFactorExpression e;
203                         
204                         while (true) {
205                                 tokenizer.GetNextToken ();
206                                 if (tokenizer.Token.Type == TokenType.RightParen) {
207                                         tokenizer.GetNextToken ();
208                                         break;
209                                 }
210                                 if (tokenizer.Token.Type == TokenType.Comma)
211                                         continue;
212                                         
213                                 tokenizer.Putback (tokenizer.Token);
214                                 e = (ConditionFactorExpression) ParseFactorExpression ();
215                                 list.Add (e);
216                         }
217                         
218                         return list;
219                 }
220
221                 //@prefix: @ or $
222                 ConditionExpression ParseReferenceExpression (string prefix)
223                 {
224                         StringBuilder sb = new StringBuilder ();
225
226                         string ref_type = prefix [0] == '$' ? "a property" : "an item list";
227                         int token_pos = tokenizer.Token.Position;
228                         IsAtToken (TokenType.LeftParen, String.Format (
229                                                 "Expected {0} at position {1} in condition \"{2}\". Missing opening parantheses after the '{3}'.",
230                                                 ref_type, token_pos, conditionStr, prefix));
231                         tokenizer.GetNextToken ();
232
233                         sb.AppendFormat ("{0}({1}", prefix, tokenizer.Token.Value);
234
235                         tokenizer.GetNextToken ();
236                         if (prefix == "@" && tokenizer.Token.Type == TokenType.Transform) {
237                                 tokenizer.GetNextToken ();
238                                 sb.AppendFormat ("->'{0}'", tokenizer.Token.Value);
239
240                                 tokenizer.GetNextToken ();
241                                 if (tokenizer.Token.Type == TokenType.Comma) {
242                                         tokenizer.GetNextToken ();
243                                         sb.AppendFormat (", '{0}'", tokenizer.Token.Value);
244                                         tokenizer.GetNextToken ();
245                                 }
246                         }
247
248                         IsAtToken (TokenType.RightParen, String.Format (
249                                                 "Expected {0} at position {1} in condition \"{2}\". Missing closing parantheses'.",
250                                                 ref_type, token_pos, conditionStr, prefix));
251                         tokenizer.GetNextToken ();
252
253                         sb.Append (")");
254
255                         //FIXME: HACKY!
256                         return new ConditionFactorExpression (new Token (sb.ToString (), TokenType.String, token_pos));
257                 }
258
259                 // used to check current token type
260                 void IsAtToken (TokenType type, string error_msg)
261                 {
262                         if (tokenizer.Token.Type != type) {
263                                 if (!String.IsNullOrEmpty (error_msg))
264                                         throw new ExpressionParseException (error_msg);
265
266                                 if (tokenizer.Token.Type == TokenType.EOF)
267                                         throw new ExpressionParseException (String.Format (
268                                                                 "Expected a \"{0}\" but the condition ended abruptly, while parsing condition \"{1}\"",
269                                                                 Token.TypeAsString (type), conditionStr));
270
271                                 throw new ExpressionParseException (String.Format (
272                                                                 "Expected \"{0}\" token,  but got {1}, while parsing \"{2}\"",
273                                                                 Token.TypeAsString (type), tokenizer.Token, conditionStr));
274                         }
275                 }
276         }
277 }