Advertisement
Guest User

Untitled

a guest
Jan 28th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 11.97 KB | None | 0 0
  1. //namespace Yard.Unger
  2.  
  3. open LanguagePrimitives
  4. //open Yard.Generators.Common.FinalGrammar
  5. open System.IO
  6.  
  7. type ProductionRule (leftHandSides : int, rightHandSides : List<int>) =
  8.        
  9.     let  leftHandSide  = leftHandSides
  10.     let rightHandSide  = rightHandSides
  11.     //new() = new ProductionRule(0, [||])
  12.     new() = new ProductionRule(0, [])
  13.     member this.getLeftHandSide() = leftHandSide
  14.     member this.getRightHandSide() = rightHandSide
  15.  
  16.     member this.equals(rule : ProductionRule) = ((rule.getLeftHandSide() = leftHandSide) && (rule.getRightHandSide() = rightHandSide))
  17.  
  18. type ProductionRule1 (leftHandSides : string, rightHandSides : List<string>) =
  19.        
  20.     let  leftHandSide  = leftHandSides
  21.     let rightHandSide  = rightHandSides
  22.     //new() = new ProductionRule(0, [||])
  23.     new() = new ProductionRule1("", [])
  24.     member this.getLeftHandSide() = leftHandSide
  25.     member this.getRightHandSide() = rightHandSide
  26.  
  27.     member this.equals(rule : ProductionRule1) = ((rule.getLeftHandSide() = leftHandSide) && (rule.getRightHandSide() = rightHandSide))
  28.  
  29.  
  30. type Goal(r : ProductionRule, p : int, l : int) =
  31.     let mutable rule : ProductionRule = r
  32.     let mutable position : int = p
  33.     let mutable length : int = l
  34.  
  35.     new() = new Goal(new ProductionRule(), 0, 0)
  36.  
  37.     member this.getRule() = rule
  38.     member this.getPosition() = position
  39.     member this.getLength() = length
  40.     member this.equals(goal : Goal) = ((goal.getPosition() = position) && (goal.getLength() = length) && (goal.getRule().equals(rule)))
  41.  
  42.  
  43. type OperationTuple(g : Goal, rp : int, ir : int) =
  44.     let mutable goal = g
  45.     let mutable rhsPosition = rp
  46.     let mutable inRec = ir
  47.  
  48.     new() = new OperationTuple(new Goal(),0,0)
  49.    
  50.     member this.getGoal() = goal
  51.     member this.getRhsPosition() = rhsPosition
  52.     member this.getInRec() = inRec
  53.  
  54.     member this.incrementRhsPosition(value : int) = rhsPosition <- rhsPosition + value;
  55.     member this.incrementInRec( value : int) = inRec <- inRec + value
  56.     member this.decrementRhsPosition(value : int) = rhsPosition <- rhsPosition - value
  57.     member this.decrementInRec (value : int) = inRec <- inRec - value
  58.  
  59. //type Grammar(grammarPath : string) =
  60. type Grammar() =
  61.  
  62.     (*let ilParser = new Yard.Frontends.YardFrontend.YardFrontend()
  63.     let il = ilParser.ParseGrammar(grammarPath)
  64.     let grammar = new FinalGrammar(il.grammar.[0].rules, true)
  65.      *)  
  66.     let mutable productionRules = []
  67.     //let mutable startSymbol : int = grammar.rules.leftSide grammar.startRule
  68.     let mutable startSymbol : int = 69
  69.     let mutable nonTerms = []
  70.     let eor = -100
  71.  
  72.    (* member this.retgr = grammar
  73.     member this.Grammar() =
  74.         for i in 0..grammar.rules.rulesCount-1 do
  75.              let lhs = grammar.rules.leftSide i
  76.              productionRules <- List.append  [new ProductionRule(lhs, (Array.append (grammar.rules.rightSide i) [|eor|]))]  productionRules
  77.              if  (nonTerms.IsEmpty) || (not (List.exists(fun x -> x = lhs) nonTerms)) then nonTerms <- List.append nonTerms [lhs]
  78.     *)
  79.    
  80.     member this.Grammar() =
  81.         this.addProductionRule("E")
  82.         this.addProductionRule("E: a;")
  83.         this.addProductionRule("E: a T;")//("E",["E";"+";"T"]) E-> Et + r
  84.         this.addProductionRule("T: a;")
  85.     member this.addProductionRule(line : string) =
  86.         if not (line.Contains(":") ) then
  87.  
  88.            startSymbol <- int(line.[0])
  89.         else
  90.             let rhs1 = List.filter (fun x -> not (x = "")) (Array.toList (line.Substring(line.IndexOf(" ") + 1).Replace("'","").Replace(";","  ;").Split(' ')))
  91.             let mutable rhs = []
  92.             for i in 0..rhs1.Length-1 do
  93.                 rhs <- List.append rhs [int(rhs1.[i].[0])]
  94.        
  95.             let lhs = int(line.[0])
  96.             productionRules <- List.append  [(new ProductionRule(lhs, rhs))]  productionRules
  97.             //productionRules <- List.append  [(new ProductionRule(lhs,rhs))]  productionRules
  98.             if  not (List.exists(fun x -> x = lhs) nonTerms) then nonTerms <- List.append nonTerms [lhs]
  99.            
  100.  
  101.     member this.getRulesForSymbol(symbol : int) =
  102.         let mutable rulesForSymbol = []
  103.         for i in 0..productionRules.Length-1 do
  104.             let rule : ProductionRule = productionRules.[i]
  105.             if (rule.getLeftHandSide() = symbol) then
  106.                 rulesForSymbol <- List.append [rule] rulesForSymbol
  107.         rulesForSymbol
  108.        
  109.     member this.getStartSymbol = startSymbol
  110.     member this.isNonTerminal (symbol : int) = List.exists (fun x-> x = symbol) nonTerms
  111.  
  112.  
  113.  
  114. type Stack<'T when 'T: equality>( st : list<'T>) =
  115.    
  116.    let mutable st = st
  117.    let popEl stk =
  118.        match stk with
  119.        |[] -> []
  120.        |_::tl -> tl
  121.  
  122.    new() = new Stack<'T>([])
  123.  
  124.     member this.peek() =
  125.         match st with
  126.         |[] -> None
  127.         |hd :: _ -> Some(hd)
  128.    
  129.     member this.push(a) = st <- a :: st
  130.    
  131.     member this.pop() =st <- popEl st
  132.  
  133.     member this.toList = st  
  134.     member this.Length() = st.Length
  135.     member this.Empty() = if st = [] then true else false
  136.  
  137. type Parser(grammar : Grammar)=
  138.     let mutable operationalStack  = new Stack<_>()
  139.     let mutable derivationStack = new Stack<_>()
  140.     let mutable parsingForest = []
  141.     let mutable grammar : Grammar = grammar
  142.     let mutable word : List<int> = []
  143.     let eor : int = -100
  144.  
  145.     let copy input =
  146.         let rec copy acc input =
  147.             match input with
  148.             |[] -> List.rev acc
  149.             |x::xs -> copy (x::acc) xs
  150.         copy [] input
  151.    
  152.     let convertSymbolToString (symbol : int) =
  153.         string(char(symbol))
  154.         (*
  155.         if symbol < grammar.indexator.nonTermCount
  156.         then grammar.indexator.indexToNonTerm symbol
  157.         elif symbol >= grammar.indexator.termsStart && symbol <= grammar.indexator.termsEnd
  158.         then grammar.indexator.indexToTerm symbol
  159.         else grammar.indexator.indexToLiteral symbol
  160.         *)
  161.     let convList (lst : List<int>) =
  162.         let mutable l = []
  163.         for i in 0..lst.Length-1 do
  164.             l <- List.append l [convertSymbolToString lst.[i]]
  165.         l
  166.  
  167.  
  168.     member this.parse(inpWord : List<string>) =
  169.         let wordConvert =
  170.             let mutable w = []
  171.             for i in 0..inpWord.Length-1 do
  172.                 w <- List.append w [int(inpWord.[i].[0])]
  173.               (*  try
  174.                       w <- List.append w [grammar.retgr.indexator.literalToIndex inpWord.[i]]
  175.                 with
  176.                      | :? System.Collections.Generic.KeyNotFoundException ->
  177.                             try
  178.                                 w <- List.append w [grammar.retgr.indexator.termToIndex inpWord.[i]]
  179.                             with
  180.                                 | :? System.Collections.Generic.KeyNotFoundException -> () *)
  181.             w
  182.         grammar.Grammar()
  183.         word <- wordConvert
  184.         this.tryAllRulesFor(grammar.getStartSymbol,0,word.Length)
  185.        
  186.    
  187.         let mutable ret = true
  188.         if parsingForest.Length = 0 then ret <- false
  189.  
  190.         let mutable derivation = [""]
  191.         let su = (parsingForest.Length) - 1
  192.         let mutable parsingForestString = []
  193.        
  194.         let pfs (parsingForest :List<List<ProductionRule>>) =
  195.             let mutable parsingForestString = []
  196.             let su = (parsingForest.Length) - 1
  197.             for i in 0..su do
  198.                 let mutable uns = []
  199.                 for j in 0..parsingForest.[i].Length-1 do
  200.                     let mutable lft = convertSymbolToString(parsingForest.[i].[j].getLeftHandSide())
  201.                     uns <- List.append uns [new ProductionRule1(lft, convList(parsingForest.[i].[j].getRightHandSide()))]
  202.                 parsingForestString <- List.append parsingForestString [uns]
  203.             parsingForestString    
  204.         let  parsingForestString = pfs parsingForest
  205.         printfn "%A" parsingForestString.Length
  206.         for i in 0..su do
  207.             derivation <-  [""]
  208.             let mutable lastString : string = string(char((grammar.getStartSymbol)))
  209.             derivation <- List.append derivation [lastString]
  210.  
  211.             let pfell = parsingForestString.[i].Length - 1
  212.             let mutable j = pfell
  213.             while j >= 0 do
  214.                 let mutable length = lastString.Length
  215.                 let mutable k = 0
  216.                 while k < length do
  217.                     if (grammar.isNonTerminal(int(lastString.[k]))) then
  218.                         let mutable ending : string = lastString.Substring(k+1)
  219.                         if (k = 0) then lastString <- "" else lastString <- lastString.Substring(0,k)
  220.                         lastString <-  lastString + (string(parsingForestString.[i].[j].getRightHandSide()).Replace("[","").Replace("]","").Replace(";","").Replace(" ","").Substring(0, (parsingForestString.[i].[j].getRightHandSide().Length - 1)))
  221.                         lastString <-  lastString  + ending
  222.                         derivation <- List.append derivation [lastString]
  223.                         k <- k + length
  224.                     else k <- k + 1
  225.                 j <- j - 1
  226.         printfn "%A" derivation.[0]
  227.  
  228.         for j in 1..(derivation.Length - 1) do
  229.             printfn " %A =>\n"  derivation.[j]
  230.         parsingForest
  231.                  
  232.  
  233.     member this.tryAllRulesFor(symbol : int, position : int, lenght : int) =
  234.  
  235.         let rulesForSymbol = grammar.getRulesForSymbol(symbol)
  236.  
  237.         for i in 0..rulesForSymbol.Length-1 do
  238.             this.tryRule(rulesForSymbol.[i],position,lenght)
  239.  
  240.     member this.tryRule(rule : ProductionRule, position : int, lenght : int) =
  241.         let goal : Goal = new Goal(rule, position, lenght)
  242.  
  243.         if (not (this.isToBeAvoided(goal)) ) then
  244.             operationalStack.push(new OperationTuple(goal , -1, 0))
  245.             derivationStack.push(rule)
  246.             this.doTopOfStack()
  247.             derivationStack.pop()
  248.             operationalStack.pop()
  249.    
  250.     member this.doTopOfStack()=
  251.         let  s : OperationTuple = operationalStack.peek().Value
  252.         let goal : Goal  = s.getGoal()
  253.         let nextRhsSymbol : int = goal.getRule().getRightHandSide().[s.getRhsPosition() + 1]
  254.         if (nextRhsSymbol = int(';')) then
  255.             if (s.getInRec() = goal.getLength()) then
  256.                 this.doNextOnStack()
  257.         else if ((s.getInRec() <  goal.getLength()) && (nextRhsSymbol = word.[goal.getPosition() + s.getInRec()])) then
  258.             s.incrementRhsPosition(1)
  259.             s.incrementInRec(1)
  260.             this.doTopOfStack()
  261.             s.decrementRhsPosition(1)
  262.             s.decrementInRec(1)
  263.         else if (grammar.isNonTerminal(nextRhsSymbol)) then
  264.             this.tryAllLengthsFor(nextRhsSymbol, goal.getPosition() + s.getInRec(), goal.getLength() - s.getInRec())
  265.  
  266.     member this.doNextOnStack()=
  267.         let s : OperationTuple = operationalStack.peek().Value
  268.         operationalStack.pop()
  269.         if (operationalStack.Empty()) then
  270.             parsingForest <-  parsingForest @ [(copy (derivationStack.toList))]
  271.         else
  272.             let s1 : OperationTuple = operationalStack.peek().Value
  273.             s1.incrementRhsPosition(1)
  274.             s1.incrementInRec(s.getGoal().getLength())
  275.             this.doTopOfStack()
  276.             s1.decrementInRec(s.getGoal().getLength())
  277.             s1.decrementRhsPosition(1)
  278.         operationalStack.push(s)
  279.  
  280.    
  281.     member this.tryAllLengthsFor(nonTerminal : int, position :  int , length : int )=
  282.  
  283.         for i in 0..length  do
  284.             this.tryAllRulesFor(nonTerminal, position, i)
  285.    
  286.     member this.isToBeAvoided(goal : Goal)=
  287.         let mutable k = false
  288.         for i in 0..(operationalStack.Length()-1) do
  289.             if (operationalStack.toList.[i].getGoal().equals(goal) = true) then  k <- true
  290.         k
  291.  
  292. let main =
  293.     //let grammar : Grammar = new Grammar("../../../../Tests/Unger/A.yrd")
  294.     let grammar = new Grammar()
  295.     let parser : Parser = new Parser(grammar)
  296.     let parsingForest = parser.parse(["r"])
  297.     parsingForest
  298. let k = main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement