33
44"""
55AST Semantic Parser (The "Rosetta Stone")
6- Version 1.0
6+ Version 1.1 - Now with Node-to-Dimension Mapping
77
88This class is the critical "bridge" in our Python Code Harmonizer.
99It walks a Python Abstract Syntax Tree (AST) and translates logical code
1010structures into the conceptual keywords understood by the
1111Divine Invitation Semantic Engine (DIVE-V2).
12+
13+ New in v1.1:
14+ - Now returns a map of {ast.Node: str} to support automated refactoring.
1215"""
1316
1417import ast
1518import re
16- from typing import List , Optional , Set
19+ from typing import Dict , List , Optional , Set , Tuple
1720
1821
1922class AST_Semantic_Parser (ast .NodeVisitor ):
@@ -29,48 +32,48 @@ def __init__(self, vocabulary: Set[str]):
2932 """
3033 self .known_vocabulary = vocabulary
3134
32- # This map translates common function name prefixes and keywords
33- # into DIVE-V2 concepts. This is the core "Intent" logic.
3435 self .intent_keyword_map = {
3536 # WISDOM (Information, Truth)
36- "get" : "information " ,
37- "read" : "information " ,
38- "fetch" : "information " ,
39- "query" : "information " ,
37+ "get" : "wisdom " ,
38+ "read" : "wisdom " ,
39+ "fetch" : "wisdom " ,
40+ "query" : "wisdom " ,
4041 "calculate" : "wisdom" ,
4142 "analyze" : "wisdom" ,
42- "validate" : "truth " ,
43- "check" : "truth " ,
44- "is_" : "truth " ,
45- "return" : "information " ,
43+ "validate" : "justice " ,
44+ "check" : "justice " ,
45+ "is_" : "justice " ,
46+ "return" : "wisdom " ,
4647 # POWER (Action, Control)
4748 "set" : "power" ,
4849 "update" : "power" ,
49- "create" : "create " ,
50- "build" : "create " ,
51- "write" : "manifest " ,
52- "delete" : "force " ,
53- "remove" : "force " ,
50+ "create" : "power " ,
51+ "build" : "power " ,
52+ "write" : "power " ,
53+ "delete" : "power " ,
54+ "remove" : "power " ,
5455 "run" : "power" ,
5556 "execute" : "power" ,
56- "raise" : "force " ,
57+ "raise" : "power " ,
5758 # JUSTICE (Order, Rules, Logic)
58- "assert" : "law " ,
59- "try" : "logic " ,
60- "except" : "mercy " , # (!)
61- "if" : "logic " ,
62- "else" : "logic " ,
63- "for" : "process " ,
64- "while" : "process " ,
65- "order" : "order " ,
59+ "assert" : "justice " ,
60+ "try" : "justice " ,
61+ "except" : "love " , # Mercy is a form of Love
62+ "if" : "justice " ,
63+ "else" : "justice " ,
64+ "for" : "justice " ,
65+ "while" : "justice " ,
66+ "order" : "justice " ,
6667 # LOVE (Unity, Connection)
67- "add" : "community" ,
68- "append" : "community" ,
69- "join" : "harmony" ,
70- "connect" : "harmony" ,
71- "merge" : "togetherness" ,
68+ "add" : "love" ,
69+ "append" : "love" ,
70+ "join" : "love" ,
71+ "connect" : "love" ,
72+ "merge" : "love" ,
73+ "print" : "love" , # Communication is a form of Love
7274 }
7375
76+ self ._node_map : Dict [ast .AST , str ] = {}
7477 self ._concepts_found : Set [str ] = set ()
7578
7679 def _split_snake_case (self , name : str ) -> List [str ]:
@@ -80,80 +83,55 @@ def _split_snake_case(self, name: str) -> List[str]:
8083 def _map_word_to_concept (self , word : str ) -> Optional [str ]:
8184 """Finds the base concept for a given word."""
8285 word_lower = word .lower ()
83-
84- # Priority 1: Direct match in the map
8586 if word_lower in self .intent_keyword_map :
8687 return self .intent_keyword_map [word_lower ]
87-
88- # Priority 2: Match in the full DIVE-V2 vocabulary
8988 if word_lower in self .known_vocabulary :
9089 return word_lower
91-
92- # Priority 3: Prefix match in the map
9390 for prefix , concept in self .intent_keyword_map .items ():
9491 if word_lower .startswith (prefix ):
9592 return concept
96-
9793 return None
9894
99- # --- PHASE 2: "INTENT" PARSING ---
100-
10195 def get_intent_concepts (
10296 self , function_name : str , docstring : Optional [str ]
10397 ) -> List [str ]:
10498 """
105- Parses the function's name and docstring to find its
106- "Stated Purpose" (Intent).
99+ Parses the function's name and docstring to find its "Stated Purpose" (Intent).
107100 """
108101 concepts : Set [str ] = set ()
109-
110- # 1. Parse the function name
111102 name_words = self ._split_snake_case (function_name )
112103 for word in name_words :
113104 concept = self ._map_word_to_concept (word )
114105 if concept :
115106 concepts .add (concept )
116-
117- # 2. Parse the docstring (as a simple bag of words)
118107 if docstring :
119108 doc_words = re .findall (r"\b\w+\b" , docstring .lower ())
120109 for word in doc_words :
121110 concept = self ._map_word_to_concept (word )
122111 if concept :
123112 concepts .add (concept )
124-
125- # Fallback: if no concepts found, use the raw words from the name
126113 if not concepts and name_words :
127114 return [word for word in name_words if word in self .known_vocabulary ]
128-
129115 return list (concepts )
130116
131- # --- PHASE 2: "EXECUTION" PARSING ---
132-
133- def get_execution_concepts (self , body : List [ast .AST ]) -> List [str ]:
117+ def get_execution_map (self , body : List [ast .AST ]) -> Tuple [Dict [ast .AST , str ], List [str ]]:
134118 """
135- Parses the function's body (a list of AST nodes) to find its
136- "Actual Action" (Execution).
137-
138- This method "walks" the AST using the ast.NodeVisitor pattern.
119+ Parses the function's body to map each AST node to a semantic dimension
120+ and return the list of concepts found.
139121 """
122+ self ._node_map = {}
140123 self ._concepts_found = set ()
141124 for node in body :
142125 self .visit (node )
143- return list (self ._concepts_found )
126+ return self . _node_map , list (self ._concepts_found )
144127
145- # --- AST "ROSETTA STONE" MAPPINGS ---
146- # These 'visit_...' methods are called by self.visit()
147- # Each one maps a Python logical structure to a DIVE-V2 concept.
128+ def _add_concept (self , node : ast .AST , concept : str ):
129+ """Helper to add a concept to both the map and the set."""
130+ self ._node_map [node ] = concept
131+ self ._concepts_found .add (concept )
148132
149133 def visit_Call (self , node : ast .Call ):
150- """
151- This is the most important node. It represents an "action"
152- (a function call).
153- """
154134 concept = None
155-
156- # Check for obj.method() calls (e.g., db.delete)
157135 if isinstance (node .func , ast .Attribute ):
158136 method_name = node .func .attr
159137 obj_name = ""
@@ -163,64 +141,44 @@ def visit_Call(self, node: ast.Call):
163141 and node .func .value .value .id == "self"
164142 ):
165143 obj_name = node .func .value .attr
166-
167- # --- CONTEXTUAL OVERRIDE (v1.4) ---
168- # If we find `self._concepts_found.add()`, this is not a "community"
169- # action, but an act of "recording information" (Wisdom).
170144 if method_name == "add" and obj_name == "_concepts_found" :
171145 concept = "wisdom"
172146 else :
173147 concept = self ._map_word_to_concept (method_name )
174-
175- # Check for simple function() calls (e.g., print)
176148 elif isinstance (node .func , ast .Name ):
177149 concept = self ._map_word_to_concept (node .func .id )
178-
179150 if concept :
180- self ._concepts_found .add (concept )
181-
182- # Continue walking *inside* the call (e.g., its arguments)
151+ self ._add_concept (node , concept )
183152 self .generic_visit (node )
184153
185154 def visit_If (self , node : ast .If ):
186- """Maps 'if' statements to 'logic' (Justice)"""
187- self ._concepts_found .add ("logic" )
155+ self ._add_concept (node , "justice" )
188156 self .generic_visit (node )
189157
190158 def visit_Assert (self , node : ast .Assert ):
191- """Maps 'assert' statements to 'truth' and 'law' (Justice)"""
192- self ._concepts_found .add ("truth" )
193- self ._concepts_found .add ("law" )
159+ self ._add_concept (node , "justice" )
194160 self .generic_visit (node )
195161
196162 def visit_Try (self , node : ast .Try ):
197- """Maps 'try/except' blocks to 'logic' and 'mercy' (Justice/Love)"""
198- self ._concepts_found .add ("logic" )
199- if node .handlers : # If there is an 'except' block
200- self ._concepts_found .add ("mercy" )
163+ self ._add_concept (node , "justice" )
164+ if node .handlers :
165+ self ._add_concept (node .handlers [0 ], "love" )
201166 self .generic_visit (node )
202167
203168 def visit_Raise (self , node : ast .Raise ):
204- """Maps 'raise' to 'power' and 'force' (Power)"""
205- self ._concepts_found .add ("power" )
206- self ._concepts_found .add ("force" )
169+ self ._add_concept (node , "power" )
207170 self .generic_visit (node )
208171
209172 def visit_For (self , node : ast .For ):
210- """Maps 'for' loops to 'process' (Justice)"""
211- self ._concepts_found .add ("process" )
173+ self ._add_concept (node , "justice" )
212174 self .generic_visit (node )
213175
214176 def visit_While (self , node : ast .While ):
215- """Maps 'while' loops to 'process' and 'control' (Justice/Power)"""
216- self ._concepts_found .add ("process" )
217- self ._concepts_found .add ("control" )
177+ self ._add_concept (node , "justice" )
218178 self .generic_visit (node )
219179
220180 def visit_Return (self , node : ast .Return ):
221- """Maps 'return' to 'information' and 'result' (Wisdom)"""
222- self ._concepts_found .add ("information" )
223- self ._concepts_found .add ("wisdom" )
181+ self ._add_concept (node , "wisdom" )
224182 self .generic_visit (node )
225183
226184 def generic_visit (self , node : ast .AST ):
0 commit comments