import { findNonSpaceTokenIndex } from "../../../common/isSpace"; import { IfNode } from "../../../nodes/nodes.type"; import { Else } from "../../../tokens"; import { BodyState } from "../../bodyState.type"; import { currentPosition } from "../../tokensState/currentToken"; import { addNode } from "../addNode"; import { treatTokenAsLiteral } from "../content/addLiteral"; import { removeIndent } from "../getIndent"; import { ChildNodesResult, getBracedChildNodes } from "./getBracedChildNodes"; import { getCondition } from "./getCondition"; export function addIfNode(state: BodyState): BodyState { const condition = getCondition(state.tokens, state.currentIndex); const children = getBracedChildNodes(state.tokens, condition.nextIndex); if (!condition.success || !children.success) { return treatTokenAsLiteral(state); } const nonSpace = findNonSpaceTokenIndex(state.tokens, children.nextIndex); if (nonSpace >= state.tokens.length || state.tokens[nonSpace].token !== Else) { return makeIfNode(state, condition.condition, children); } const elseChildren = getBracedChildNodes(state.tokens, nonSpace + 1); if (!elseChildren.success) { return makeIfNode(state, condition.condition, children); } if (children.isMultiline || elseChildren.isMultiline) { state = removeIndent(state); } const node = new IfNode(condition.condition, children.nodes, elseChildren.nodes, currentPosition(state)); return addNode(state, elseChildren.nextIndex, node); } function makeIfNode(state: BodyState, condition: string, children: ChildNodesResult): BodyState { if (children.isMultiline) { state = removeIndent(state); } const node = new IfNode(condition, children.nodes, [], currentPosition(state)); return addNode(state, children.nextIndex, node); }