MCPcopy Create free account
hub / github.com/SeaOfNodes/Simple / parseIf

Method parseIf

chapter15/src/main/java/com/seaofnodes/simple/Parser.java:365–404  ·  view source on GitHub ↗

Parses a statement if ( expression ) statement [else statement] @return a Node, never null

()

Source from the content-addressed store, hash-verified

363 * @return a {@link Node}, never {@code null}
364 */
365 private Node parseIf() {
366 require("(");
367 // Parse predicate
368 var pred = require(parseExpression(), ")").keep();
369 // IfNode takes current control and predicate
370 Node ifNode = new IfNode(ctrl(), pred).peephole();
371 // Setup projection nodes
372 Node ifT = new CProjNode(ifNode. keep(), 0, "True" ).peephole().keep();
373 Node ifF = new CProjNode(ifNode.unkeep(), 1, "False").peephole().keep();
374 // In if true branch, the ifT proj node becomes the ctrl
375 // But first clone the scope and set it as current
376 int ndefs = _scope.nIns();
377 ScopeNode fScope = _scope.dup(); // Duplicate current scope
378 _xScopes.push(fScope); // For graph visualization we need all scopes
379
380 // Parse the true side
381 ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
382 _scope.upcast(ifT,pred,false); // Up-cast predicate
383 parseStatement(); // Parse true-side
384 ScopeNode tScope = _scope;
385
386 // Parse the false side
387 _scope = fScope; // Restore scope, then parse else block if any
388 ctrl(ifF.unkeep()); // Ctrl token is now set to ifFalse projection
389 _scope.upcast(ifF,pred,true); // Up-cast predicate
390 if (matchx("else")) {
391 parseStatement();
392 fScope = _scope;
393 }
394 pred.unkeep();
395
396 if( tScope.nIns() != ndefs || fScope.nIns() != ndefs )
397 throw error("Cannot define a new name on one arm of an if");
398
399 // Merge results
400 _scope = tScope;
401 _xScopes.pop(); // Discard pushed from graph display
402
403 return ctrl(tScope.mergeScopes(fScope));
404 }
405
406
407 /**

Callers 1

parseStatementMethod · 0.95

Calls 15

requireMethod · 0.95
keepMethod · 0.95
parseExpressionMethod · 0.95
ctrlMethod · 0.95
unkeepMethod · 0.95
parseStatementMethod · 0.95
matchxMethod · 0.95
errorMethod · 0.95
mergeScopesMethod · 0.95
peepholeMethod · 0.45
nInsMethod · 0.45
dupMethod · 0.45

Tested by

no test coverage detected