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

Method parseIf

chapter16/src/main/java/com/seaofnodes/simple/Parser.java:339–378  ·  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

337 * <pre>
338 * if ( expression ) statement [else statement]
339 * </pre>
340 * @return a {@link Node}, never {@code null}
341 */
342 private Node parseIf() {
343 require("(");
344 // Parse predicate
345 var pred = require(parseExpression(), ")").keep();
346 // IfNode takes current control and predicate
347 Node ifNode = new IfNode(ctrl(), pred).peephole();
348 // Setup projection nodes
349 Node ifT = new CProjNode(ifNode. keep(), 0, "True" ).peephole().keep();
350 Node ifF = new CProjNode(ifNode.unkeep(), 1, "False").peephole().keep();
351 // In if true branch, the ifT proj node becomes the ctrl
352 // But first clone the scope and set it as current
353 int ndefs = _scope.nIns();
354 ScopeNode fScope = _scope.dup(); // Duplicate current scope
355 fScope.ctrl(ifF); // The pending arm already starts at False
356 _xScopes.push(fScope); // For graph visualization we need all scopes
357
358 // Parse the true side
359 ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
360 _scope.upcast(ifT,pred,false); // Up-cast predicate
361 parseStatement(); // Parse true-side
362 ScopeNode tScope = _scope;
363
364 // Parse the false side
365 _scope = fScope; // Restore scope, then parse else block if any
366 ifF.unkeep(); // fScope already owns the false control
367 _scope.upcast(ifF,pred,true); // Up-cast predicate
368 if (matchx("else")) {
369 parseStatement();
370 fScope = _scope;
371 }
372 pred.unkeep();
373
374 if( tScope.nIns() != ndefs || fScope.nIns() != ndefs )
375 throw error("Cannot define a new name on one arm of an if");
376
377 // Merge results
378 _scope = tScope;
379 _xScopes.pop(); // Discard pushed from graph display
380
381 return ctrl(tScope.mergeScopes(fScope));

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