on-Haeya / pre-python-viz

0 stars 0 forks source link

별찍기 시각화 #4

Closed ujkkk closed 2 weeks ago

ujkkk commented 2 weeks ago

📝 Description

무엇을?

왜?

❗️Todo

ETC

기타사항

SongGwanSeok commented 2 weeks ago

별찍기 json 구조


  "steps": [
    {
      "type": "Assign",
      "id": "a",
      "value": 3
    },
    {
      "type": "For",
      "exprs": [
        {
          "for_var": [
            {
              "type": "Assign",
              "id": "i",
              "value": 0
            },
            {
              "type": "Assign",
              "id": "start",
              "value": 0
            },
            {
              "type": "Assign",
              "id": "end",
              "value": 2
            }
          ],
          "body": [
            {
              "type": "func",
              "name": "print",
              "value": [
                "'*' * (i+1)",
                "'*' * 1",
                "'*'"
              ]
            }
          ]
        },
        {
          "for_var": [
            {
              "type": "Assign",
              "id": "i",
              "value": 1
            }
          ],
          "body": [
            {
              "type": "func",
              "name": "print",
              "value": [
                "'*' * (i+1)",
                "'*' * 2",
                "'**'"
              ]
            }
          ]
        },
        {
          "for_var": [
            {
              "type": "Assign",
              "id": "i",
              "value": 2
            }
          ],
          "body": [
            {
              "type": "func",
              "name": "print",
              "value": [
                "'*' * (i+1)",
                "'*' * 3",
                "'***'"
              ]
            }
          ]
        }
      ]
    }
  ]
}```
ujkkk commented 2 weeks ago

` @dataclass class Target: id: str type: str

@dataclass class Value: exp: str eval: str

AST 노드를 순회하면서 실행

for node in parsed_ast.body:
    # 변수 선언 및 할당 처리
    if isinstance(node, ast.Assign):
        for target in node.targets:
            eval_value = eval(compile(ast.Expression(node.value), '', 'eval'), global_vars, local_vars)
            # 표현식 추출
            expression = ast.unparse(node.value) if hasattr(ast, 'unparse') else compile(ast.Expression(node.value),
                                                                                         '', 'eval').co_code
            target_obj = Target(id=target.id, type=get_type_string(eval_value))
            value_obj = Value(exp=expression, eval=eval_value)

            # json 형식 생성
            json_output = create_json(target_obj, value_obj)
            print(json_output)`