def test_codegen_decrease_indent(self) -> None: state = WhitespaceInclusivePositionProvidingCodegenState( " " * 4, "\n", WhitespaceInclusivePositionProvider() ) state.increase_indent(state.default_indent) state.increase_indent(state.default_indent) state.increase_indent(state.default_indent) state.decrease_indent() state.add_indent_tokens() self.assertEqual(position(state), (1, 8))
def code_for_node( self, node: CSTNode, provider: Optional["_PositionProviderUnion"] = None) -> str: """ Generates the code for the given node in the context of this module. This is a method of Module, not CSTNode, because we need to know the module's default indentation and newline formats. This can also be used with a :class:`~libcst.metadata.PositionProvider` or a :class:`~libcst.metadata.WhitespaceInclusivePositionProvider` to compute position information, but that's an implementation detail, and you should use :meth:`MetadataWrapper.resolve() <libcst.metadata.MetadataWrapper.resolve>` instead. See :ref:`Metadata<libcst-metadata>` for more information. """ from libcst.metadata.position_provider import PositionProvider if provider is None: state = CodegenState( default_indent=self.default_indent, default_newline=self.default_newline, provider=provider, ) elif isinstance(provider, PositionProvider): state = PositionProvidingCodegenState( default_indent=self.default_indent, default_newline=self.default_newline, provider=provider, ) else: state = WhitespaceInclusivePositionProvidingCodegenState( default_indent=self.default_indent, default_newline=self.default_newline, provider=provider, ) node._codegen(state) return "".join(state.tokens)
def test_whitespace_inclusive_position(self) -> None: # create a dummy node node = cst.Pass() # simulate codegen behavior for the dummy node # generates the code " pass " state = WhitespaceInclusivePositionProvidingCodegenState( " " * 4, "\n", WhitespaceInclusivePositionProvider() ) start = CodePosition(state.line, state.column) state.add_token(" ") with state.record_syntactic_position(node): state.add_token("pass") state.add_token(" ") end = CodePosition(state.line, state.column) state.record_position(node, CodeRange(start, end)) # check whitespace is correctly recorded self.assertEqual(state.provider._computed[node], CodeRange((1, 0), (1, 6)))
def test_codegen_add_newline(self) -> None: state = WhitespaceInclusivePositionProvidingCodegenState( " " * 4, "\n", WhitespaceInclusivePositionProvider() ) state.add_token("\n") self.assertEqual(position(state), (2, 0))
def test_codegen_initial_position(self) -> None: state = WhitespaceInclusivePositionProvidingCodegenState( " " * 4, "\n", WhitespaceInclusivePositionProvider() ) self.assertEqual(position(state), (1, 0))