Repository navigation
Expand file tree
/
Copy pathParserSupport.java
More file actions
1607 lines (1322 loc) · 62.9 KB
/
Copy pathParserSupport.java
File metadata and controls
1607 lines (1322 loc) · 62.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006-2007 Mirko Stocker <me@misto.ch>
* Copyright (C) 2006 Thomas Corbat <tcorbat@hsr.ch>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.parser;
import java.math.BigInteger;
import org.jcodings.Encoding;
import org.jruby.CompatVersion;
import org.jruby.RubyBignum;
import org.jruby.RubyRegexp;
import org.jruby.ast.*;
import org.jruby.ast.types.ILiteralNode;
import org.jruby.ast.types.INameNode;
import org.jruby.common.IRubyWarnings;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.lexer.yacc.ISourcePosition;
import org.jruby.lexer.yacc.ISourcePositionHolder;
import org.jruby.lexer.yacc.RubyYaccLexer;
import org.jruby.lexer.yacc.SyntaxException;
import org.jruby.lexer.yacc.Token;
import org.jruby.lexer.yacc.SyntaxException.PID;
import org.jruby.runtime.DynamicScope;
import org.jruby.util.ByteList;
import org.jruby.util.IdUtil;
import org.jruby.util.RegexpOptions;
import org.jruby.util.StringSupport;
/**
*
*/
public class ParserSupport {
// Parser states:
protected StaticScope currentScope;
protected RubyYaccLexer lexer;
// Is the parser current within a singleton (value is number of nested singletons)
private int inSingleton;
// Is the parser currently within a method definition
private boolean inDefinition;
protected IRubyWarnings warnings;
protected ParserConfiguration configuration;
private RubyParserResult result;
public void reset() {
inSingleton = 0;
inDefinition = false;
}
public void allowDubyExtension(ISourcePosition position) {
throw new SyntaxException(PID.DUBY_EXTENSIONS_OFF, position,
lexer.getCurrentLine(), "Duby extensions not configured");
}
public StaticScope getCurrentScope() {
return currentScope;
}
public ParserConfiguration getConfiguration() {
return configuration;
}
public void popCurrentScope() {
currentScope = currentScope.getEnclosingScope();
}
public void pushBlockScope() {
currentScope = configuration.getRuntime().getStaticScopeFactory().newBlockScope(currentScope);
}
public void pushLocalScope() {
currentScope = configuration.getRuntime().getStaticScopeFactory().newLocalScope(currentScope);
}
public Node arg_concat(ISourcePosition position, Node node1, Node node2) {
return node2 == null ? node1 : new ArgsCatNode(position, node1, node2);
}
public Node arg_blk_pass(Node firstNode, BlockPassNode secondNode) {
if (secondNode != null) {
secondNode.setArgsNode(firstNode);
return secondNode;
}
return firstNode;
}
/**
* We know for callers of this that it cannot be any of the specials checked in gettable.
*
* @param node to check its variable type
* @return an AST node representing this new variable
*/
public Node gettable2(Node node) {
switch (node.getNodeType()) {
case DASGNNODE: // LOCALVAR
case LOCALASGNNODE:
return currentScope.declare(node.getPosition(), ((INameNode) node).getName());
case CONSTDECLNODE: // CONSTANT
return new ConstNode(node.getPosition(), ((INameNode) node).getName());
case INSTASGNNODE: // INSTANCE VARIABLE
return new InstVarNode(node.getPosition(), ((INameNode) node).getName());
case CLASSVARDECLNODE:
case CLASSVARASGNNODE:
return new ClassVarNode(node.getPosition(), ((INameNode) node).getName());
case GLOBALASGNNODE:
return new GlobalVarNode(node.getPosition(), ((INameNode) node).getName());
}
getterIdentifierError(node.getPosition(), ((INameNode) node).getName());
return null;
}
/**
* Create AST node representing variable type it represents.
*
* @param token to check its variable type
* @return an AST node representing this new variable
*/
public Node gettable(Token token) {
switch (token.getType()) {
case Tokens.kSELF:
return new SelfNode(token.getPosition());
case Tokens.kNIL:
return new NilNode(token.getPosition());
case Tokens.kTRUE:
return new TrueNode(token.getPosition());
case Tokens.kFALSE:
return new FalseNode(token.getPosition());
case Tokens.k__FILE__:
return new FileNode(token.getPosition(), new ByteList(token.getPosition().getFile().getBytes(),
getConfiguration().getRuntime().getEncodingService().getLocaleEncoding()));
case Tokens.k__LINE__:
return new FixnumNode(token.getPosition(), token.getPosition().getStartLine()+1);
case Tokens.k__ENCODING__:
return new EncodingNode(token.getPosition(), lexer.getEncoding());
case Tokens.tIDENTIFIER:
return currentScope.declare(token.getPosition(), (String) token.getValue());
case Tokens.tCONSTANT:
return new ConstNode(token.getPosition(), (String) token.getValue());
case Tokens.tIVAR:
return new InstVarNode(token.getPosition(), (String) token.getValue());
case Tokens.tCVAR:
return new ClassVarNode(token.getPosition(), (String) token.getValue());
case Tokens.tGVAR:
return new GlobalVarNode(token.getPosition(), (String) token.getValue());
}
getterIdentifierError(token.getPosition(), (String) token.getValue());
return null;
}
protected void getterIdentifierError(ISourcePosition position, String identifier) {
throw new SyntaxException(PID.BAD_IDENTIFIER, position, lexer.getCurrentLine(),
"identifier " + identifier + " is not valid", identifier);
}
public AssignableNode assignable(Token lhs, Node value) {
checkExpression(value);
switch (lhs.getType()) {
case Tokens.kSELF:
throw new SyntaxException(PID.CANNOT_CHANGE_SELF, lhs.getPosition(),
lexer.getCurrentLine(), "Can't change the value of self");
case Tokens.kNIL:
throw new SyntaxException(PID.INVALID_ASSIGNMENT, lhs.getPosition(),
lexer.getCurrentLine(), "Can't assign to nil", "nil");
case Tokens.kTRUE:
throw new SyntaxException(PID.INVALID_ASSIGNMENT, lhs.getPosition(),
lexer.getCurrentLine(), "Can't assign to true", "true");
case Tokens.kFALSE:
throw new SyntaxException(PID.INVALID_ASSIGNMENT, lhs.getPosition(),
lexer.getCurrentLine(), "Can't assign to false", "false");
case Tokens.k__FILE__:
throw new SyntaxException(PID.INVALID_ASSIGNMENT, lhs.getPosition(),
lexer.getCurrentLine(), "Can't assign to __FILE__", "__FILE__");
case Tokens.k__LINE__:
throw new SyntaxException(PID.INVALID_ASSIGNMENT, lhs.getPosition(),
lexer.getCurrentLine(), "Can't assign to __LINE__", "__LINE__");
case Tokens.tIDENTIFIER:
return currentScope.assign(lhs.getPosition(), (String) lhs.getValue(), makeNullNil(value));
case Tokens.tCONSTANT:
if (isInDef() || isInSingle()) {
throw new SyntaxException(PID.DYNAMIC_CONSTANT_ASSIGNMENT, lhs.getPosition(),
lexer.getCurrentLine(), "dynamic constant assignment");
}
return new ConstDeclNode(lhs.getPosition(), (String) lhs.getValue(), null, value);
case Tokens.tIVAR:
return new InstAsgnNode(lhs.getPosition(), (String) lhs.getValue(), value);
case Tokens.tCVAR:
if (isInDef() || isInSingle()) {
return new ClassVarAsgnNode(lhs.getPosition(), (String) lhs.getValue(), value);
}
return new ClassVarDeclNode(lhs.getPosition(), (String) lhs.getValue(), value);
case Tokens.tGVAR:
return new GlobalAsgnNode(lhs.getPosition(), (String) lhs.getValue(), value);
}
throw new SyntaxException(PID.BAD_IDENTIFIER, lhs.getPosition(), lexer.getCurrentLine(),
"identifier " + (String) lhs.getValue() + " is not valid", lhs.getValue());
}
/**
* Wraps node with NEWLINE node.
*
*@param node
*@return a NewlineNode or null if node is null.
*/
public Node newline_node(Node node, ISourcePosition position) {
if (node == null) return null;
configuration.coverLine(position.getStartLine());
return node instanceof NewlineNode ? node : new NewlineNode(position, node);
}
public Node addRootNode(Node topOfAST, ISourcePosition position) {
position = topOfAST != null ? topOfAST.getPosition() : position;
if (result.getBeginNodes().isEmpty()) {
if (topOfAST == null) topOfAST = NilImplicitNode.NIL;
return new RootNode(position, result.getScope(), topOfAST);
}
BlockNode newTopOfAST = new BlockNode(position);
for (Node beginNode: result.getBeginNodes()) {
appendToBlock(newTopOfAST, beginNode);
}
// Add real top to new top (unless this top is empty [only begin/end nodes or truly empty])
if (topOfAST != null) newTopOfAST.add(topOfAST);
return new RootNode(position, result.getScope(), newTopOfAST);
}
/* MRI: block_append */
public Node appendToBlock(Node head, Node tail) {
if (tail == null) return head;
if (head == null) return tail;
// Reduces overhead in interp by not set position every single line we encounter.
if (!configuration.hasExtraPositionInformation()) {
head = compactNewlines(head);
}
if (!(head instanceof BlockNode)) {
head = new BlockNode(head.getPosition()).add(head);
}
if (warnings.isVerbose() && isBreakStatement(((ListNode) head).getLast())) {
warnings.warning(ID.STATEMENT_NOT_REACHED, tail.getPosition(), "Statement not reached.");
}
// Assumption: tail is never a list node
((ListNode) head).addAll(tail);
return head;
}
public Node getOperatorCallNode(Node firstNode, String operator) {
checkExpression(firstNode);
return new CallNoArgNode(firstNode.getPosition(), firstNode, operator);
}
public Node getOperatorCallNode(Node firstNode, String operator, Node secondNode) {
return getOperatorCallNode(firstNode, operator, secondNode, null);
}
public Node getOperatorCallNode(Node firstNode, String operator, Node secondNode, ISourcePosition defaultPosition) {
if (defaultPosition != null) {
firstNode = checkForNilNode(firstNode, defaultPosition);
secondNode = checkForNilNode(secondNode, defaultPosition);
}
checkExpression(firstNode);
checkExpression(secondNode);
return new_call_one_arg(firstNode.getPosition(), firstNode, operator, secondNode);
// return new CallOneArgNode(firstNode.getPosition(), firstNode, operator, new ArrayNode(secondNode.getPosition(), secondNode));
}
public Node getMatchNode(Node firstNode, Node secondNode) {
if (firstNode instanceof DRegexpNode || firstNode instanceof RegexpNode) {
return new Match2Node(firstNode.getPosition(), firstNode, secondNode);
} else if (secondNode instanceof DRegexpNode || secondNode instanceof RegexpNode) {
return new Match3Node(firstNode.getPosition(), secondNode, firstNode);
}
return getOperatorCallNode(firstNode, "=~", secondNode);
}
/**
* Define an array set condition so we can return lhs
*
* @param receiver array being set
* @param index node which should evalute to index of array set
* @return an AttrAssignNode
*/
public Node aryset(Node receiver, Node index) {
checkExpression(receiver);
return new_attrassign(receiver.getPosition(), receiver, "[]=", index);
}
/**
* Define an attribute set condition so we can return lhs
*
* @param receiver object which contains attribute
* @param name of the attribute being set
* @return an AttrAssignNode
*/
public Node attrset(Node receiver, String name) {
checkExpression(receiver);
return new_attrassign(receiver.getPosition(), receiver, name + "=", null);
}
public void backrefAssignError(Node node) {
if (node instanceof NthRefNode) {
String varName = "$" + ((NthRefNode) node).getMatchNumber();
throw new SyntaxException(PID.INVALID_ASSIGNMENT, node.getPosition(),
"Can't set variable " + varName + '.', varName);
} else if (node instanceof BackRefNode) {
String varName = "$" + ((BackRefNode) node).getType();
throw new SyntaxException(PID.INVALID_ASSIGNMENT, node.getPosition(), "Can't set variable " + varName + '.', varName);
}
}
public Node arg_add(ISourcePosition position, Node node1, Node node2) {
if (node1 == null) {
if (node2 == null) {
return new ArrayNode(position, NilImplicitNode.NIL);
} else {
return new ArrayNode(node2.getPosition(), node2);
}
}
if (node1 instanceof ArrayNode) return ((ArrayNode) node1).add(node2);
return new ArgsPushNode(position, node1, node2);
}
/**
* @fixme position
**/
public Node node_assign(Node lhs, Node rhs) {
if (lhs == null) return null;
Node newNode = lhs;
checkExpression(rhs);
if (lhs instanceof AssignableNode) {
((AssignableNode) lhs).setValueNode(rhs);
} else if (lhs instanceof IArgumentNode) {
IArgumentNode invokableNode = (IArgumentNode) lhs;
return invokableNode.setArgsNode(arg_add(lhs.getPosition(), invokableNode.getArgsNode(), rhs));
}
return newNode;
}
public Node ret_args(Node node, ISourcePosition position) {
if (node != null) {
if (node instanceof BlockPassNode) {
throw new SyntaxException(PID.DYNAMIC_CONSTANT_ASSIGNMENT, position,
lexer.getCurrentLine(), "Dynamic constant assignment.");
} else if (node instanceof ArrayNode && ((ArrayNode)node).size() == 1) {
node = ((ArrayNode)node).get(0);
} else if (node instanceof SplatNode) {
node = newSValueNode(position, node);
}
}
return node;
}
/**
* Is the supplied node a break/control statement?
*
* @param node to be checked
* @return true if a control node, false otherwise
*/
public boolean isBreakStatement(Node node) {
breakLoop: do {
if (node == null) return false;
switch (node.getNodeType()) {
case NEWLINENODE:
node = ((NewlineNode) node).getNextNode();
continue breakLoop;
case BREAKNODE: case NEXTNODE: case REDONODE:
case RETRYNODE: case RETURNNODE:
return true;
default:
return false;
}
} while (true);
}
public void warnUnlessEOption(ID id, Node node, String message) {
if (!configuration.isInlineSource()) {
warnings.warn(id, node.getPosition(), message);
}
}
public void warningUnlessEOption(ID id, Node node, String message) {
if (warnings.isVerbose() && !configuration.isInlineSource()) {
warnings.warning(id, node.getPosition(), message);
}
}
private Node compactNewlines(Node head) {
while (head instanceof NewlineNode) {
Node nextNode = ((NewlineNode) head).getNextNode();
if (!(nextNode instanceof NewlineNode)) {
break;
}
head = nextNode;
}
return head;
}
// logical equivalent to value_expr in MRI
public boolean checkExpression(Node node) {
boolean conditional = false;
while (node != null) {
switch (node.getNodeType()) {
case DEFNNODE: case DEFSNODE:
warnings.warning(ID.VOID_VALUE_EXPRESSION, node.getPosition(),
"void value expression");
return false;
case RETURNNODE: case BREAKNODE: case NEXTNODE: case REDONODE:
case RETRYNODE:
if (!conditional) {
throw new SyntaxException(PID.VOID_VALUE_EXPRESSION,
node.getPosition(), lexer.getCurrentLine(),
"void value expression");
}
return false;
case BLOCKNODE:
node = ((BlockNode) node).getLast();
break;
case BEGINNODE:
node = ((BeginNode) node).getBodyNode();
break;
case IFNODE:
if (!checkExpression(((IfNode) node).getThenBody())) return false;
node = ((IfNode) node).getElseBody();
break;
case ANDNODE: case ORNODE:
conditional = true;
node = ((BinaryOperatorNode) node).getSecondNode();
break;
case NEWLINENODE:
node = ((NewlineNode) node).getNextNode();
break;
default: // Node
return true;
}
}
return true;
}
/**
* Is this a literal in the sense that MRI has a NODE_LIT for. This is different than
* ILiteralNode. We should pick a different name since ILiteralNode is something we created
* which is similiar but used for a slightly different condition (can I do singleton things).
*
* @param node to be tested
* @return true if it is a literal
*/
public boolean isLiteral(Node node) {
return node != null && (node instanceof FixnumNode || node instanceof BignumNode ||
node instanceof FloatNode || node instanceof SymbolNode ||
(node instanceof RegexpNode && ((RegexpNode) node).getOptions().toJoniOptions() == 0));
}
private void handleUselessWarn(Node node, String useless) {
warnings.warn(ID.USELESS_EXPRESSION, node.getPosition(), "Useless use of " + useless + " in void context.");
}
/**
* Check to see if current node is an useless statement. If useless a warning if printed.
*
* @param node to be checked.
*/
public void checkUselessStatement(Node node) {
if (!warnings.isVerbose() || (!configuration.isInlineSource() && configuration.isEvalParse())) return;
uselessLoop: do {
if (node == null) return;
switch (node.getNodeType()) {
case NEWLINENODE:
node = ((NewlineNode) node).getNextNode();
continue uselessLoop;
case CALLNODE: {
String name = ((CallNode) node).getName();
if (name == "+" || name == "-" || name == "*" || name == "/" || name == "%" ||
name == "**" || name == "+@" || name == "-@" || name == "|" || name == "^" ||
name == "&" || name == "<=>" || name == ">" || name == ">=" || name == "<" ||
name == "<=" || name == "==" || name == "!=") {
handleUselessWarn(node, name);
}
return;
}
case BACKREFNODE: case DVARNODE: case GLOBALVARNODE:
case LOCALVARNODE: case NTHREFNODE: case CLASSVARNODE:
case INSTVARNODE:
handleUselessWarn(node, "a variable"); return;
// FIXME: Temporarily disabling because this fires way too much running Rails tests. JRUBY-518
/*case CONSTNODE:
handleUselessWarn(node, "a constant"); return;*/
case BIGNUMNODE: case DREGEXPNODE: case DSTRNODE: case DSYMBOLNODE:
case FIXNUMNODE: case FLOATNODE: case REGEXPNODE:
case STRNODE: case SYMBOLNODE:
handleUselessWarn(node, "a literal"); return;
// FIXME: Temporarily disabling because this fires way too much running Rails tests. JRUBY-518
/*case CLASSNODE: case COLON2NODE:
handleUselessWarn(node, "::"); return;*/
case DOTNODE:
handleUselessWarn(node, ((DotNode) node).isExclusive() ? "..." : ".."); return;
case DEFINEDNODE:
handleUselessWarn(node, "defined?"); return;
case FALSENODE:
handleUselessWarn(node, "false"); return;
case NILNODE:
handleUselessWarn(node, "nil"); return;
// FIXME: Temporarily disabling because this fires way too much running Rails tests. JRUBY-518
/*case SELFNODE:
handleUselessWarn(node, "self"); return;*/
case TRUENODE:
handleUselessWarn(node, "true"); return;
default: return;
}
} while (true);
}
/**
* Check all nodes but the last one in a BlockNode for useless (void context) statements.
*
* @param blockNode to be checked.
*/
public void checkUselessStatements(BlockNode blockNode) {
if (warnings.isVerbose()) {
Node lastNode = blockNode.getLast();
for (int i = 0; i < blockNode.size(); i++) {
Node currentNode = blockNode.get(i);
if (lastNode != currentNode ) {
checkUselessStatement(currentNode);
}
}
}
}
/**
* assign_in_cond
**/
private boolean checkAssignmentInCondition(Node node) {
if (node instanceof MultipleAsgnNode) {
throw new SyntaxException(PID.MULTIPLE_ASSIGNMENT_IN_CONDITIONAL, node.getPosition(),
lexer.getCurrentLine(), "Multiple assignment in conditional.");
} else if (node instanceof LocalAsgnNode || node instanceof DAsgnNode || node instanceof GlobalAsgnNode || node instanceof InstAsgnNode) {
Node valueNode = ((AssignableNode) node).getValueNode();
if (valueNode instanceof ILiteralNode || valueNode instanceof NilNode || valueNode instanceof TrueNode || valueNode instanceof FalseNode) {
warnings.warn(ID.ASSIGNMENT_IN_CONDITIONAL, node.getPosition(), "Found '=' in conditional, should be '=='.");
}
return true;
}
return false;
}
protected Node makeNullNil(Node node) {
return node == null ? NilImplicitNode.NIL : node;
}
private Node cond0(Node node) {
checkAssignmentInCondition(node);
Node leftNode = null;
Node rightNode = null;
// FIXME: DSTR,EVSTR,STR: warning "string literal in condition"
switch(node.getNodeType()) {
case DREGEXPNODE: {
ISourcePosition position = node.getPosition();
return new Match2Node(position, node, new GlobalVarNode(position, "$_"));
}
case ANDNODE:
leftNode = cond0(((AndNode) node).getFirstNode());
rightNode = cond0(((AndNode) node).getSecondNode());
return new AndNode(node.getPosition(), makeNullNil(leftNode), makeNullNil(rightNode));
case ORNODE:
leftNode = cond0(((OrNode) node).getFirstNode());
rightNode = cond0(((OrNode) node).getSecondNode());
return new OrNode(node.getPosition(), makeNullNil(leftNode), makeNullNil(rightNode));
case DOTNODE: {
DotNode dotNode = (DotNode) node;
if (dotNode.isLiteral()) return node;
String label = String.valueOf("FLIP" + node.hashCode());
currentScope.getLocalScope().addVariable(label);
int slot = currentScope.isDefined(label);
return new FlipNode(node.getPosition(),
getFlipConditionNode(((DotNode) node).getBeginNode()),
getFlipConditionNode(((DotNode) node).getEndNode()),
dotNode.isExclusive(), slot);
}
case REGEXPNODE:
warningUnlessEOption(ID.REGEXP_LITERAL_IN_CONDITION, node, "regex literal in condition");
return new MatchNode(node.getPosition(), node);
}
return node;
}
public Node getConditionNode(Node node) {
if (node == null) return NilImplicitNode.NIL;
if (node instanceof NewlineNode) {
return new NewlineNode(node.getPosition(), cond0(((NewlineNode) node).getNextNode()));
}
return cond0(node);
}
/* MRI: range_op */
private Node getFlipConditionNode(Node node) {
if (!configuration.isInlineSource()) return node;
node = getConditionNode(node);
if (node instanceof NewlineNode) return ((NewlineNode) node).getNextNode();
if (node instanceof FixnumNode) {
warnUnlessEOption(ID.LITERAL_IN_CONDITIONAL_RANGE, node, "integer literal in conditional range");
return getOperatorCallNode(node, "==", new GlobalVarNode(node.getPosition(), "$."));
}
return node;
}
public SValueNode newSValueNode(ISourcePosition position, Node node) {
return new SValueNode(position, node);
}
public SplatNode newSplatNode(ISourcePosition position, Node node) {
return new SplatNode(position, makeNullNil(node));
}
public ArrayNode newArrayNode(ISourcePosition position, Node firstNode) {
return new ArrayNode(position, makeNullNil(firstNode));
}
public ISourcePosition position(ISourcePositionHolder one, ISourcePositionHolder two) {
return one == null ? two.getPosition() : one.getPosition();
}
public AndNode newAndNode(ISourcePosition position, Node left, Node right) {
checkExpression(left);
if (left == null && right == null) return new AndNode(position, makeNullNil(left), makeNullNil(right));
return new AndNode(position(left, right), makeNullNil(left), makeNullNil(right));
}
public OrNode newOrNode(ISourcePosition position, Node left, Node right) {
checkExpression(left);
if (left == null && right == null) return new OrNode(position, makeNullNil(left), makeNullNil(right));
return new OrNode(position(left, right), makeNullNil(left), makeNullNil(right));
}
/**
* Ok I admit that this is somewhat ugly. We post-process a chain of when nodes and analyze
* them to re-insert them back into our new CaseNode the way we want. The grammar is being
* difficult and until I go back into the depths of that this is where things are.
*
* @param expression of the case node (e.g. case foo)
* @param firstWhenNode first when (which could also be the else)
* @return a new case node
*/
public CaseNode newCaseNode(ISourcePosition position, Node expression, Node firstWhenNode) {
ArrayNode cases = new ArrayNode(firstWhenNode != null ? firstWhenNode.getPosition() : position);
CaseNode caseNode = new CaseNode(position, expression, cases);
for (Node current = firstWhenNode; current != null; current = ((WhenNode) current).getNextCase()) {
if (current instanceof WhenOneArgNode) {
cases.add(current);
} else if (current instanceof WhenNode) {
simplifyMultipleArgumentWhenNodes((WhenNode) current, cases);
} else {
caseNode.setElseNode(current);
break;
}
}
return caseNode;
}
/*
* This method exists for us to break up multiple expression when nodes (e.g. when 1,2,3:)
* into individual whenNodes. The primary reason for this is to ensure lazy evaluation of
* the arguments (when foo,bar,gar:) to prevent side-effects. In the old code this was done
* using nested when statements, which was awful for interpreter and compilation.
*
* Notes: This has semantic equivalence but will not be lexically equivalent. Compiler
* needs to detect same bodies to simplify bytecode generated.
*/
private void simplifyMultipleArgumentWhenNodes(WhenNode sourceWhen, ArrayNode cases) {
Node expressionNodes = sourceWhen.getExpressionNodes();
if (expressionNodes instanceof SplatNode || expressionNodes instanceof ArgsCatNode) {
cases.add(sourceWhen);
return;
}
if (expressionNodes instanceof ListNode) {
ListNode list = (ListNode) expressionNodes;
ISourcePosition position = sourceWhen.getPosition();
Node bodyNode = sourceWhen.getBodyNode();
for (int i = 0; i < list.size(); i++) {
Node expression = list.get(i);
if (expression instanceof SplatNode || expression instanceof ArgsCatNode) {
cases.add(new WhenNode(position, expression, bodyNode, null));
} else {
cases.add(new WhenOneArgNode(position, expression, bodyNode, null));
}
}
} else {
cases.add(sourceWhen);
}
}
public WhenNode newWhenNode(ISourcePosition position, Node expressionNodes, Node bodyNode, Node nextCase) {
if (bodyNode == null) bodyNode = NilImplicitNode.NIL;
if (expressionNodes instanceof SplatNode || expressionNodes instanceof ArgsCatNode || expressionNodes instanceof ArgsPushNode) {
return new WhenNode(position, expressionNodes, bodyNode, nextCase);
}
ListNode list = (ListNode) expressionNodes;
if (list.size() == 1) {
Node element = list.get(0);
if (!(element instanceof SplatNode)) {
return new WhenOneArgNode(position, element, bodyNode, nextCase);
}
}
return new WhenNode(position, expressionNodes, bodyNode, nextCase);
}
public Node getReturnArgsNode(Node node) {
if (node instanceof ArrayNode && ((ArrayNode) node).size() == 1) {
return ((ListNode) node).get(0);
} else if (node instanceof BlockPassNode) {
throw new SyntaxException(PID.BLOCK_ARG_UNEXPECTED, node.getPosition(),
lexer.getCurrentLine(), "Block argument should not be given.");
}
return node;
}
public Node new_opAssign(AssignableNode lhs, String asgnOp, Node rhs) {
checkExpression(rhs);
ISourcePosition pos = lhs.getPosition();
if (asgnOp.equals("||")) {
lhs.setValueNode(rhs);
return new OpAsgnOrNode(pos, gettable2(lhs), lhs);
} else if (asgnOp.equals("&&")) {
lhs.setValueNode(rhs);
return new OpAsgnAndNode(pos, gettable2(lhs), lhs);
}
lhs.setValueNode(getOperatorCallNode(gettable2(lhs), asgnOp, rhs));
lhs.setPosition(pos);
return lhs;
}
public Node new_opElementAsgnNode(ISourcePosition position, Node receiverNode, String operatorName, Node argsNode, Node valueNode) {
if (argsNode instanceof ArrayNode) {
ArrayNode array = (ArrayNode) argsNode;
if (array.size() == 1) {
if (operatorName.equals("||")) {
return new OpElementOneArgOrAsgnNode(position, receiverNode, operatorName, array, valueNode);
} else if (operatorName.equals("&&")) {
return new OpElementOneArgAndAsgnNode(position, receiverNode, operatorName, array, valueNode);
} else {
return new OpElementOneArgAsgnNode(position, receiverNode, operatorName, array, valueNode);
}
}
}
return new OpElementAsgnNode(position, receiverNode, operatorName, argsNode, valueNode);
}
public Node new_attrassign(ISourcePosition position, Node receiver, String name, Node args) {
if (!(args instanceof ArrayNode)) return new AttrAssignNode(position, receiver, name, args);
ArrayNode argsNode = (ArrayNode) args;
switch (argsNode.size()) {
case 1:
return new AttrAssignOneArgNode(position, receiver, name, argsNode);
case 2:
return new AttrAssignTwoArgNode(position, receiver, name, argsNode);
case 3:
return new AttrAssignThreeArgNode(position, receiver, name, argsNode);
default:
return new AttrAssignNode(position, receiver, name, argsNode);
}
}
private Node new_call_noargs(Node receiver, Token name, IterNode iter) {
ISourcePosition position = position(receiver, name);
if (receiver == null) receiver = NilImplicitNode.NIL;
if (iter != null) return new CallNoArgBlockNode(position, receiver, (String) name.getValue(), iter);
return new CallNoArgNode(position, receiver, (String) name.getValue());
}
private Node new_call_complexargs(Node receiver, Token name, Node args, Node iter) {
if (args instanceof BlockPassNode) {
// Block and block pass passed in at same time....uh oh
if (iter != null) {
throw new SyntaxException(PID.BLOCK_ARG_AND_BLOCK_GIVEN, iter.getPosition(),
lexer.getCurrentLine(), "Both block arg and actual block given.");
}
return new_call_blockpass(receiver, name, (BlockPassNode) args);
}
if (iter != null) return new CallSpecialArgBlockNode(position(receiver, args), receiver,(String) name.getValue(), args, (IterNode) iter);
return new CallSpecialArgNode(position(receiver, args), receiver, (String) name.getValue(), args);
}
private Node new_call_blockpass(Node receiver, Token operation, BlockPassNode blockPass) {
ISourcePosition position = position(receiver, blockPass);
String name = (String) operation.getValue();
Node args = blockPass.getArgsNode();
if (args == null) return new CallNoArgBlockPassNode(position, receiver, name, args, blockPass);
if (!(args instanceof ArrayNode)) return new CallSpecialArgBlockPassNode(position, receiver, name, args, blockPass);
switch (((ArrayNode) args).size()) {
case 0: // foo()
return new CallNoArgBlockPassNode(position, receiver, name, args, blockPass);
case 1:
return new CallOneArgBlockPassNode(position, receiver, name, (ArrayNode) args, blockPass);
case 2:
return new CallTwoArgBlockPassNode(position, receiver, name, (ArrayNode) args, blockPass);
case 3:
return new CallThreeArgBlockPassNode(position, receiver, name, (ArrayNode) args, blockPass);
default:
return new CallManyArgsBlockPassNode(position, receiver, name, args, blockPass);
}
}
private boolean isNumericOperator(String name) {
if (name.length() == 1) {
switch (name.charAt(0)) {
case '+': case '-': case '*': case '/': case '<': case '>':
return true;
}
} else if (name.length() == 2) {
switch (name.charAt(0)) {
case '<': case '>': case '=':
switch (name.charAt(1)) {
case '=': case '<':
return true;
}
}
}
return false;
}
private Node new_call_one_arg(ISourcePosition position, Node receiver, String name, Node first) {
if (first instanceof FixnumNode && isNumericOperator(name)) {
return new CallOneArgFixnumNode(position, receiver, name, new ArrayNode(position, first));
}
return new CallOneArgNode(position, receiver, name, new ArrayNode(position, first));
}
public Node new_call(Node receiver, Token name, Node argsNode, Node iter) {
if (argsNode == null) return new_call_noargs(receiver, name, (IterNode) iter);
if (!(argsNode instanceof ArrayNode)) return new_call_complexargs(receiver, name, argsNode, iter);
ArrayNode args = (ArrayNode) argsNode;
switch (args.size()) {
case 0:
if (iter != null) return new CallNoArgBlockNode(position(receiver, args), receiver, (String) name.getValue(), args, (IterNode) iter);
return new CallNoArgNode(position(receiver, args), receiver, args, (String) name.getValue());
case 1:
if (iter != null) return new CallOneArgBlockNode(position(receiver, args), receiver, (String) name.getValue(), args, (IterNode) iter);
return new CallOneArgNode(position(receiver, args), receiver, (String) name.getValue(), args);
case 2:
if (iter != null) return new CallTwoArgBlockNode(position(receiver, args), receiver, (String) name.getValue(), args, (IterNode) iter);
return new CallTwoArgNode(position(receiver, args), receiver, (String) name.getValue(), args);
case 3:
if (iter != null) return new CallThreeArgBlockNode(position(receiver, args), receiver, (String) name.getValue(), args, (IterNode) iter);
return new CallThreeArgNode(position(receiver, args), receiver, (String) name.getValue(), args);
default:
if (iter != null) return new CallManyArgsBlockNode(position(receiver, args), receiver, (String) name.getValue(), args, (IterNode) iter);
return new CallManyArgsNode(position(receiver, args), receiver, (String) name.getValue(), args);
}
}
public Node new_aref(Node receiver, Token name, Node argsNode) {
if (argsNode instanceof ArrayNode) {
ArrayNode args = (ArrayNode) argsNode;
if (args.size() == 1 && args.get(0) instanceof FixnumNode) {
return new CallOneArgFixnumNode(position(receiver, args), receiver, "[]", args);
}
}
return new_call(receiver, name, argsNode, null);
}
public Colon2Node new_colon2(ISourcePosition position, Node leftNode, String name) {
if (IdUtil.isConstant(name)) {
if (leftNode == null) return new Colon2ImplicitNode(position, name);
return new Colon2ConstNode(position, leftNode, name);
}
return new Colon2MethodNode(position, leftNode, name);
}
public Colon3Node new_colon3(ISourcePosition position, String name) {
return new Colon3Node(position, name);
}
private Node new_fcall_noargs(Token operation, IterNode iter) {
if (iter != null) return new FCallNoArgBlockNode(operation.getPosition(), (String) operation.getValue(), iter);
return new FCallNoArgNode(operation.getPosition(), (String) operation.getValue());