-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoq2c.hs
1367 lines (1124 loc) · 57.9 KB
/
coq2c.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- |
-- Module : Extractor (Main)
-- Copyright : Veïs Oudjail 2016
-- License : CeCILL
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : multi plateform
--
-- Description : Compiler Coq (AST JSON) -> subset C
--
-- This software is a computer program whose purpose is to run a minimal,
-- hypervisor relying on proven properties such as memory isolation.
-- This software is governed by the CeCILL license under French law and
-- abiding by the rules of distribution of free software. You can use,
-- modify and/ or redistribute the software under the terms of the CeCILL
-- license as circulated by CEA, CNRS and INRIA at the following URL
-- "http://www.cecill.info".
-- As a counterpart to the access to the source code and rights to copy,
-- modify and redistribute granted by the license, users are provided only
-- with a limited warranty and the software's author, the holder of the
-- economic rights, and the successive licensors have only limited
-- liability.
-- In this respect, the user's attention is drawn to the risks associated
-- with loading, using, modifying and/or developing or reproducing the
-- software by the user in light of its specific status of free software,
-- that may mean that it is complicated to manipulate, and that also
-- therefore means that it is reserved for developers and experienced
-- professionals having in-depth computer knowledge. Users are therefore
-- encouraged to load and test the software's suitability as regards their
-- requirements in conditions enabling the security of their systems and/or
-- data to be ensured and, more generally, to use and operate it in the
-- same conditions as regards security.
-- The fact that you are presently reading this means that you have had
-- knowledge of the CeCILL license and that you accept its terms.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative
import Control.Monad (zipWithM, join)
import Data.Aeson
import Data.Bool (bool)
import Data.Char (toUpper)
import Data.List (intercalate, union, find)
import Data.List.Split (splitOn)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Options.Applicative (strArgument,strOption,short,long,metavar,optional,help)
import System.Environment (getProgName)
import Text.Regex.Posix ((=~))
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Options.Applicative as OA
concatMapM :: (Functor m, Monad m) => (a -> m [b]) -> [a] -> m [b]
concatMapM f = fmap concat . mapM f
----------- Module ASTCoq -----------------
-- Ce type peut-être interprété comme une énumération.
-- Chacun de ses éléments représente une entité de l'arbre syntaxique Coq.
data WhatT = DeclT DeclT | FixgrpT FixgrpT | TypeT TypeT
| ExprT ExprT | CaseT | PatT PatT
| ModuleT
deriving (Show)
data DeclT = TermDT | FixgrpDT
deriving (Show)
data FixgrpT = ItemFT
deriving (Show)
data TypeT = ArrowTT | GlobTT | VaridxTT
deriving (Show)
data ExprT = LambdaET| ApplyET | GlobalET | ConstructorET | RelET | CaseET | LetET
deriving (Show)
data PatT = ConstructorPT | WildPT
deriving (Show)
instance FromJSON WhatT where
parseJSON (Object v) = toWhatType <$> v .: "what"
parseJSON _ = fail "Error, WhatType : undefined !"
-- Fonction qui permet de transformer les étiquettes dans le type enuméré
toWhatType :: String -> WhatT
toWhatType strType =
case strType of
"case" -> CaseT
"module" -> ModuleT
"decl:term" -> DeclT TermDT
"decl:fixgroup" -> DeclT FixgrpDT
"fixgroup:item" -> FixgrpT ItemFT
"type:arrow" -> TypeT ArrowTT
"type:glob" -> TypeT GlobTT
"type:varidx" -> TypeT VaridxTT
"expr:lambda" -> ExprT LambdaET
"expr:apply" -> ExprT ApplyET
"expr:global" -> ExprT GlobalET
"expr:constructor" -> ExprT ConstructorET
"expr:rel" -> ExprT RelET
"expr:case" -> ExprT CaseET
"expr:let" -> ExprT LetET
"pat:constructor" -> PatT ConstructorPT
"pat:wild" -> PatT WildPT
strError -> error $ "Error WhatType : " ++ strError ++ " format undefined"
--------------------------------------------------------------
data Decl = Term { nameTerm :: String
, typeTerm :: Type
, valueTerm :: Expr
}
| Fixgroup { fixlistFixgroup :: [Fixgroup]
}
deriving (Show)
instance FromJSON Decl where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
DeclT TermDT ->
Term <$>
v .: "name" <*>
v .: "type" <*>
v .: "value"
DeclT FixgrpDT ->
Fixgroup <$>
v .: "fixlist"
_ -> fail "Error, Decl : case undefined !"
parseJSON _ = fail "Error, Decl : undefined !"
data Fixgroup = Item { nameItem :: String
, typeItem :: Type
, valueItem :: Expr
}
deriving (Show)
instance FromJSON Fixgroup where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
FixgrpT ItemFT ->
Item <$>
v .: "name" <*>
v .: "type" <*>
v .: "value"
_ -> fail "Error, Fixgroup : case undefined !"
parseJSON _ = fail "Error, Fixgroup : undefined !"
data Type = Arrow { leftArrow :: Type
, rightLeft :: Type
}
| Glob { nameGlob :: String
, argsGlob :: [Type]
}
| Varidx { nameVaridx :: Integer
}
deriving (Show)
instance FromJSON Type where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
TypeT ArrowTT ->
Arrow <$>
v .: "left" <*>
v .: "right"
TypeT GlobTT ->
Glob <$>
v .: "name" <*>
v .: "args"
TypeT VaridxTT ->
Varidx <$>
v .: "name"
_ -> fail "Error, Type : case undefined !"
parseJSON _ = fail "Error, Type : undefined !"
data Expr = Lambda { argnamesLambda :: [String]
, bodyLambda :: Expr
}
| Apply { funcApply :: Expr
, argsApply :: [Expr]
}
| Global { nameGlobal :: String
}
| ConstructorE { nameConstructorE :: String
, argsConstructorE :: [Expr]
}
| Rel { nameRel :: String
}
| Case { exprCase :: Expr
, casesCase :: [Case]
}
| Let { nameLet :: String
, namevalLet :: Expr
, bodyLet :: Expr
}
deriving (Show)
instance FromJSON Expr where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
ExprT LambdaET ->
Lambda <$>
v .: "argnames" <*>
v .: "body"
ExprT ApplyET ->
Apply <$>
v .: "func" <*>
v .: "args"
ExprT GlobalET ->
Global <$>
v .: "name"
ExprT ConstructorET ->
ConstructorE <$>
v .: "name" <*>
v .: "args"
ExprT RelET ->
Rel <$>
v .: "name"
ExprT CaseET ->
Case <$>
v .: "expr" <*>
v .: "cases"
ExprT LetET ->
Let <$>
v .: "name" <*>
v .: "nameval" <*>
v .: "body"
_ -> fail "Error, Expr : case undefined !"
parseJSON _ = fail "Error, Expr : undefined !"
data Case = C { patC :: Pat
, bodyC :: Expr
}
deriving (Show)
instance FromJSON Case where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
CaseT ->
C <$>
v .: "pat" <*>
v .: "body"
_ -> fail "Error, Case : case undefined !"
parseJSON _ = fail "Error, Case : undefined !"
data Pat = ConstructorP { nameConstructorP :: String
, argnamesConstructorP :: [String]
}
| WildP
deriving (Show)
instance FromJSON Pat where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
PatT ConstructorPT ->
ConstructorP <$>
v .: "name" <*>
v .: "argnames"
PatT WildPT -> return WildP
_ -> fail "Error, Pat : case undefined !"
parseJSON _ = fail "Error, Pat : undefined !"
data Module = Mod { nameMod :: String
, needMagicMod :: Bool
, needDummyMod :: Bool
, usedModulesMod :: [ModuleUsed]
, declarationsMod :: [Decl]
}
deriving (Show)
type ModuleUsed = String
type FileName = String
instance FromJSON Module where
parseJSON (Object v) =
do what <- toWhatType <$> v .: "what"
case what of
ModuleT ->
Mod <$>
v .: "name" <*>
v .: "need_magic" <*>
v .: "need_dummy" <*>
v .: "used_modules" <*>
v .: "declarations"
_ -> fail "Error, Module : case undefined !"
parseJSON _ = fail "Error, Module : undefined !"
data ASTCoq = ModuleAST Module
| TypeAST Type
| ExprAST Expr
| CaseAST Case
| DeclAST Decl
| FixgroupAST Fixgroup
| PatAST Pat
--------------------- Monad MyEither -----------------------------------
-- Définition du type Monadique, représente le resultat de transformation.
-- Cela marche comme la monade Maybe. La différence vient du fait que lorsque l'on echoue
-- on peut l'associé à un message d'erreur.
-- Pour ce faire on definie un nouveau type, qui est un wrapper sur le type Either
newtype MyEither a = MyEith (Either String a)
deriving (Show)
instance Functor MyEither where
fmap f (MyEith me) = case me of
Left l -> MyEith $ Left l
Right r -> MyEith $ Right (f r)
instance Applicative MyEither where
pure = MyEith . Right
(MyEith f) <*> (MyEith (Right r)) = case f of
Left l -> MyEith $ Left l
Right f' -> MyEith $ Right (f' r)
_ <*> (MyEith (Left l)) = MyEith $ Left l
instance Monad MyEither where
return = pure
fail = MyEith . Left
(MyEith me) >>= f = case me of
Left l -> MyEith $ Left l
Right r -> f r
-- Fonction qui permet de transformer une monade Maybe en une monade MyEither
-- @param strErr : Représente le message d'erreur, si la monade est dans un etat d'echec
-- @param maybe : Représente la monade Maybe qui sera convertit
-- @return : On retourne une entité MyEither construite à partir des param fixé
toMyEith :: String -> Maybe a -> MyEither a
toMyEith strErr Nothing = fail strErr
toMyEith _ (Just x) = return x
-- Même principe que pour la fonction toMyEith, à la différence que le message d'erreur n'est pas renseigné
toMyEith' :: Maybe a -> MyEither a
toMyEith' = toMyEith ""
-- Getteur, permet d'extraire du type MyEither l'objet de type either
myEither :: MyEither a -> Either String a
myEither (MyEith x) = x
-- Cette fonction permet d'ajouter un message d'erreur si le contexte générale est dans un etat d'echec
-- @param trace : Message d'erreur à ajouter
-- @param myEith : Représente le contexte, si l'etat est dans un mode echec, on ajoute un message d'erreur
-- @return : Retourne le contexte, avec potentiellement l'ajout d'un nouveau message
addTraceMyEith :: String -> MyEither b -> MyEither b
addTraceMyEith trace (MyEith (Left x)) = fail $ trace ++ "\n" ++ x
addTraceMyEith _ x = x
-- Cet opérateur permet de combiner different contexte. La combinaison ce fait comme un 'ou'.
-- Si le contexte de gauche echoue, on renvoie le contexte de droite, et inversemement.
infixr 2 |||
(|||) :: MyEither a -> MyEither a -> MyEither a
(MyEith (Left err)) ||| y = addTraceMyEith err y
x ||| _ = x
------------------- Module ASTC -----------------------------------------
-- Définition des différente entité correspondant à l'arbre syntaxique du sous-ensemble C
data FunctionC = FunctionC { prototypeFun :: PrototypeC
, bodyFun :: [InstructionC]
}
deriving (Show, Eq)
data PrototypeC = PrototypeC { nameProto :: String
, returnTypeProto :: TypeC
, argsProto :: [DeclVarC]
}
deriving (Show, Eq)
data InstructionC = CSC { cSC :: ControlStructC
}
| ExprC { exprC :: ExprC
}
| DeclVarC { declVarC :: DeclVarC
}
| ReturnC { returnC :: ExprC
}
deriving (Show, Eq)
data ControlStructC = Iter { iterC :: IterativeStructC
}
| Cond { condC :: ConditionalStructC
}
deriving (Show, Eq)
data IterativeStructC = WhileC { conditionWhile :: ExprC
, bodyWhile :: [InstructionC]
}
deriving (Show, Eq)
data ConditionalStructC = IfThenElseC { conditionIf :: ExprC
, bodyThen :: [InstructionC]
, bodyElse :: [InstructionC]
}
deriving (Show, Eq)
data ExprC = ApplyFunC { funApplyFun :: String
, argsApplyFun :: [ExprC]
}
| BinOp { leftBO :: ExprC
, symboleBO :: String
, rightBO :: ExprC
}
| VarC { varC :: VarC
}
| ValC { valC :: ValC
}
deriving (Show, Eq)
data DeclC = VarCDecl { varCDecl :: DeclVarC
}
| FunDecl { funDecl :: FunctionC
}
| ObjectDecl { objectDecl :: DeclObjectC
}
| ProtoDecl { protoDecl :: PrototypeC
}
| CommDecl { commDecl :: CommentaryC
}
deriving (Show, Eq)
data DeclVarC = VarEmptyDecl { lvalueEDecl :: VarC
}
| VarDecl { lvalueDecl :: VarC
, rvalueDecl :: ExprC
}
deriving (Show, Eq)
data DeclObjectC = StructDecl { nameStructDecl :: String
, bodyStructDecl :: [DeclVarC]
}
| EnumDecl { nameEnumDecl :: String
, bodyEnumDecl :: [String]
}
deriving (Show, Eq)
data ModuleC = ModuleC FileName FileH FileC
deriving (Show, Eq)
data FileC = FileC { includeFC :: [IncludeC]
, bodyFC :: [DeclC]
}
deriving (Show, Eq)
type FileH = FileC
data IncludeC = GloIncC String
| LocIncC String
deriving (Show, Eq, Read)
data TypeC = TypeC String
| TypeCFun [TypeC]
deriving (Show, Eq)
type CommentaryC = String
type DataC = String
type NameC = String
type MacroIncBegin = String
type MacroIncEnd = String
type VarC = (NameC, TypeC)
type ValC = (DataC, TypeC)
----------- Definition du type Parser ----------------------
data ParseError = PE_NOT_IF_THEN_ELSE
type Parser a b = (a -> MyEither b)
typeVoid :: TypeC
typeVoid = TypeC "void"
bodyLambdaM :: Expr -> MyEither Expr
bodyLambdaM (Lambda _ b) = (MyEith . Right) b
bodyLambdaM _ = fail "bodyLambdaM, fail : "
lvalueOfDeclV :: DeclVarC -> VarC
lvalueOfDeclV (VarEmptyDecl v) = v
lvalueOfDeclV (VarDecl v _) = v
isDeclFun :: DeclC -> Bool
isDeclFun (FunDecl _) = True
isDeclFun _ = False
isDeclObjectC :: DeclC -> Bool
isDeclObjectC (ObjectDecl _) = True
isDeclObjectC _ = False
isTypeCFun :: TypeC -> Bool
isTypeCFun (TypeCFun _) = True
isTypeCFun _ = False
typeRetTypeC :: TypeC -> TypeC
typeRetTypeC (TypeCFun t) = last t
typeRetTypeC t@TypeC{} = t
elmTypeC :: TypeC -> [TypeC]
elmTypeC (TypeCFun t) = t
elmTypeC t@TypeC{} = [t]
prototypeOfDeclC :: [DeclC] -> [PrototypeC]
prototypeOfDeclC ldecl = map (prototypeFun . funDecl) lfun
where lfun = filter isDeclFun ldecl
objectCOfDeclC :: [DeclC] -> [DeclObjectC]
objectCOfDeclC ldecl = map objectDecl (filter isDeclObjectC ldecl)
clearPref :: NameCoq -> NameC
clearPref = last . (splitOn ".")
addDeclCToFileC :: FileC -> [DeclC] -> FileH
addDeclCToFileC (FileC incC's declC'ss) declC's = FileC incC's (declC's ++ declC'ss)
addDeclCToModCFileH :: ModuleC -> [DeclC] -> ModuleC
addDeclCToModCFileH (ModuleC n fH fC) declC's = ModuleC n (addDeclCToFileC fH declC's) fC
------------- Module Env -----------------------------------
-- Ce module permet de definir les structures modélisant l'environnement du traducteur.
-- Definition des synonymes de types utilisés pour définir l'environnement
type NameCoqType = String
type NameCoqFun = String
type NameCoqConstruct = String
type SymbolBinOp = String
type NameCFun = String
type NameCoq = String
-------------------------------------------------------------------------------
-- Cette objet represente les differente formes que l'on peux prendre dans l'environnement utilisateur
-- Forme NewTypeEUI :
---- Cela représente ...
-- Forme NewFunEUI
---- Cela représente ...
-- Forme NewVarEUI
---- Cela représente ...
-- Forme OpBinEUI
---- Cela représente ...
-- Forme IncludeListEUI
---- Cela représente ...
data EnvUserItem = NewTypeEUI { nameCoqNNEUI :: NameCoq
, pTypeNNEUI :: EnvG -> Parser (Either Type Expr) TypeC
, pValCNNEUI :: [(NameCoqConstruct, NameCoq -> EnvG -> Parser Expr ExprC)]
}
| NewFunEUI { nameCoqNNEUI :: NameCoq
, nameCNNEUI :: NameC
, pTypeNNEUI :: EnvG -> Parser (Either Type Expr) TypeC
, nArgsNNEUI :: Int
}
| NewVarEUI { nameCoqNVEUI :: NameCoq
, newDeclVarC :: DeclVarC
}
| OpBinEUI { nameCoqOBEUI :: NameCoq
, nameCOBEUI :: SymbolBinOp
, pTypeOBEUI :: EnvG -> Parser (Either Type Expr) TypeC
}
| IncludeListEUI { nameModuleEUI :: ModuleUsed
, includeListEUI :: [(NameCoq, [IncludeC])]
}
data EnvArgs = EnvArgs { importOpt :: [String]
, gloIncOpt :: [String]
, locIncOpt :: [String]
, headerOpt :: Maybe String
, outputOpt :: Maybe String
, outputHOpt :: Maybe String
, inputOpt :: String
}
data EnvTypeItem = ETI { idET :: String, funET :: EnvG -> Parser (Either Type Expr) TypeC }
instance Eq EnvTypeItem where
(ETI id' _) == (ETI id'' _) = id' == id''
instance Show EnvTypeItem where
show (ETI id' _) = id'
type EnvVarC = [DeclVarC]
type EnvType = [EnvTypeItem]
type EnvChangeName = [(NameCoqFun, NameCFun)]
newtype EnvValC = EVC { evc :: [(NameCoqConstruct, EnvG -> Parser Expr ExprC)]}
newtype EnvFunApply = EFA [EnvG -> Parser Expr ExprC]
type EnvG = (EnvVarC, EnvType, EnvValC, EnvFunApply, EnvChangeName)
type EnvUser = [EnvUserItem]
instance Show EnvValC where
show (EVC l) = show $ map fst l
----------------------------------------------
type EnvIncG = [(String, [IncludeC])]
type EnvBinOp = [(NameCoqFun, SymbolBinOp)]
newtype EnvCondC = EC [EnvG -> ExprC -> Parser Pat ([DeclVarC], Maybe ExprC)]
----------------------------------------------
type ExprValC = ExprC
lookupEnvV :: Expr -> EnvG -> MyEither (Parser Expr ExprValC)
lookupEnvV (ConstructorE k _) env@(_,_,ev,_,_) = toMyEith "lookupEnvV undefined, constructor case" $ lookup (clearPref k) (evc ev) <*> return env
lookupEnvV _ _ = fail "lookupEnvV undefined"
lookupEnvT :: String -> EnvG -> MyEither (Parser (Either Type Expr) TypeC)
lookupEnvT k env@(_,et,_,_,_) = toMyEith ("lookupEnvT undefined, key : " ++ (clearPref k)) $ lookup (clearPref k) $ map (\(ETI k' f )-> (k', f env)) et
lookupEnvVar :: NameCoq -> EnvG -> MyEither TypeC
lookupEnvVar name (ev,_,_,_,_) = toMyEith "lookupEnvVar undefined" $ lookup (clearPref name) (map lvalueOfDeclV ev)
lookupEnvN :: NameCoq -> EnvG -> MyEither NameC
lookupEnvN nCoq (_,_,_,_,en) = toMyEith "lookupEnvN undefined" $ lookup (clearPref nCoq) en
lookupEnvBinOp :: NameCoq -> EnvBinOp -> MyEither NameC
lookupEnvBinOp k envbop = toMyEith "lookupEnvBinOp undefined" $ lookup (clearPref k) envbop
lookupEnvInc :: ModuleUsed -> ModuleUsed -> EnvUser -> MyEither [IncludeC]
lookupEnvInc mu minc eu = toMyEith "lookupEnvInc undefined" body
where inclL = filter (\x -> case x of {IncludeListEUI{} -> True; _ -> False}) eu
itemInc = find ((mu ==) . nameModuleEUI) inclL
body = do einc <- includeListEUI <$> itemInc
lookup minc einc
lookupEnvIncG :: ModuleUsed -> EnvIncG -> MyEither [IncludeC]
lookupEnvIncG minc einc = toMyEith "lookupEnvInc undefined" $ lookup minc einc
-- lookupReverseEnvN :: NameC -> EnvG -> MyEither NameCoq
-- lookupReverseEnvN nC (_,_,_,_,en) = toMyEith "lookupReverseEnvN undefined" $ lookup (clearPref nC) $ map (\(a,b) -> (b,a)) en
-- existNameCEnvN :: NameC -> EnvG -> Bool
-- existNameCEnvN nC env = (isRight . myEither) . lookupReverseEnvN nC env
runParserEnvT :: String -> EnvG -> Parser (Either Type Expr) TypeC
runParserEnvT k env eith = join $ (\f -> f eith) <$> lookupEnvT k env
runParserEnvV :: EnvG -> Parser Expr ExprValC
runParserEnvV env expr = join $ (\f -> f expr) <$> lookupEnvV expr env
runParserEnvFApply :: EnvG -> Parser Expr ExprC
runParserEnvFApply env@(_,_,_,EFA efa,_) c = foldr (\f fs -> f env c ||| fs) (fail "runParserEnvFApply undefined") efa
runParserEnvCondC :: EnvG -> EnvCondC -> ExprC -> Parser Pat ([DeclVarC], Maybe ExprC)
runParserEnvCondC env (EC envc) expr pat = foldr (\f fs -> f env expr pat ||| fs) (fail "runParserEnvCondC undefined") envc
retConstPType :: String -> TypeC -> EnvTypeItem
retConstPType nameCoq typeC = ETI nameCoq (\_ _ -> return typeC)
retValC :: DataC -> NameCoq -> Expr -> EnvG -> MyEither ExprC
retValC dataC nC c@(ConstructorE _ args) env = ValC . (,) dataC <$> pCaseIfArgs
where pCaseIfArgs = bool (parseExprOfTypeC env c) -- case False
(parseTypeC env (Glob nC [])) $ null args
retValC _ _ _ _ = fail "retValC undefined"
mergeEnvG :: EnvG -> EnvG -> EnvG
mergeEnvG (ev, et, ec, ef, en) (ev', et', _, _, _) = (ev' `union` ev, et `union` et', ec, ef, en)
addVarsCEnvG :: EnvG -> EnvVarC -> EnvG
addVarsCEnvG (v, t, ec, ef, en) e = (e ++ v, t, ec, ef, en)
addTypeCEnvT :: EnvG -> EnvType -> EnvG
addTypeCEnvT (v, t, ec, ef, en) e = (v, t `union` e, ec, ef, en)
envTypeG :: EnvG -> EnvType
envTypeG (_, envt, _, _, _) = envt
----------------------
envUser :: EnvUser
envUser = [ NewTypeEUI "bool" pBoolC [("Coq_true", pTrueValC), ("Coq_false", pFalseValC)]
, NewTypeEUI "unit" pVoidC [("Coq_tt", pVoidValC)]
, NewTypeEUI "nat" pUnsignedC [("O", pOValC), ("S", pSValC)]
, NewTypeEUI "coq_LLI" pLLIOfTypeC []
, NewTypeEUI "index" pUint32C []
, NewTypeEUI "page" pUintPtrC []
, NewTypeEUI "vaddr" pUintPtrC []
, NewTypeEUI "level" pUint32C []
, NewTypeEUI "count" pUint32C []
, OpBinEUI "orb" "||" pBoolC
, OpBinEUI "eqb" "==" pBoolC
, OpBinEUI "andb" "&&" pBoolC
--, OpBinEUI "sub" "-" pUnsignedC
, OpBinEUI "gtbLevel" ">" pBoolC
, OpBinEUI "gtbIndex" ">" pBoolC
, OpBinEUI "ltbIndex" "<" pBoolC
, OpBinEUI "gebIndex" ">=" pBoolC
, OpBinEUI "lebIndex" "<=" pBoolC
, OpBinEUI "indexEq" "==" pBoolC
, OpBinEUI "levelEq" "==" pBoolC
, OpBinEUI "gebCount" ">=" pBoolC
--, NewFunEUI "coq_Kidx" "Kidx" pUint32C 0
, NewFunEUI "negb" "!" pBoolC 1
, NewFunEUI "ret" "" pRetOfTypeC 1
, NewFunEUI "i" "" pIOfTypeC 1
----------------------------- Mal --------------------------------------------
, NewFunEUI "nb_level" "nb_level" pUnsignedC 0
, NewFunEUI "table_size" "table_size" pUnsignedC 0
, NewFunEUI "fstLevel" "fstLevel" pUint32C 0
{-
, NewFunEUI "writePhyEntry" "writePhysicalWithLotsOfFlags" pVoidC 8
, NewFunEUI "writeVirEntry" "writePhysical" pVoidC 3
, NewFunEUI "readPhyEntry" "readPhysical" pUintPtrC 2
, NewFunEUI "readVirEntry" "readPhysical" pUintPtrC 2
, NewFunEUI "getNbLevel" "getNbIndex" pUint32C 0
, NewFunEUI "getIndexOfAddr" "getIndexOfAddr" pUint32C 2
, NewFunEUI "readPhysical" "readPhysical" pUintPtrC 2
, NewFunEUI "writePhysical" "writePhysical" pVoidC 3
, NewFunEUI "readVirtual" "readPhysical" pUintPtrC 2
, NewFunEUI "writeVirtual" "writePhysical" pVoidC 3
, NewFunEUI "fetchVirtual" "readVirtual" pUintPtrC 2
, NewFunEUI "storeVirtual" "writeVirtual" pVoidC 3
, NewFunEUI "readIndex" "readIndex" pUint32C 2
, NewFunEUI "writeIndex" "writeIndex" pVoidC 3
, NewFunEUI "readPresent" "readPresent" pBoolC 2
, NewFunEUI "writePresent" "writePresent" pVoidC 3
, NewFunEUI "readAccessible" "readAccessible" pBoolC 2
, NewFunEUI "writeAccessible" "writeAccessible" pVoidC 3
, NewFunEUI "derivated" "derivated" pBoolC 2
, NewFunEUI "writePDflag" "writePDflag" pVoidC 3
, NewFunEUI "readPDflag" "readPDflag" pBoolC 2
, NewFunEUI "getCurPartition" "get_current_pd" pUintPtrC 0
, NewFunEUI "defaultPhysical" "defaultAddr" pUintPtrC 0
, NewFunEUI "defaultVirtual" "defaultAddr" pUintPtrC 0
, NewFunEUI "getMaxIndex" "getMaxIndex" pUint32C 0
, NewFunEUI "addressEqualsPhy" "addressEquals" pBoolC 2
, NewFunEUI "addressEqualsVir" "addressEquals" pBoolC 2
, NewFunEUI "getIndex" "toAddr" pUint32C 1
, NewFunEUI "checkRights" "checkRights" pBoolC 3
, NewFunEUI "levelPred" "sub" pUint32C 1
, NewFunEUI "levelSucc" "inc" pUint32C 1
, NewFunEUI "indexZero" "indexZero" pUint32C 0
, NewFunEUI "indexKernel" "kernelIndex" pUint32C 0
, NewFunEUI "indexPR" "kernelIndex" pUint32C 0
, NewFunEUI "indexPD" "kernelIndex" pUint32C 0
, NewFunEUI "indexSh1" "kernelIndex" pUint32C 0
, NewFunEUI "indexSh2" "kernelIndex" pUint32C 0
, NewFunEUI "indexSh3" "kernelIndex" pUint32C 0
, NewFunEUI "indexPRP" "kernelIndex" pUint32C 0
, NewFunEUI "indexPred" "sub" pUint32C 1
, NewFunEUI "indexSucc" "inc" pUint32C 1
, NewFunEUI "levelToCountProd3" "levelToCountProd3" pUint32C 1
, NewFunEUI "countZero" "indexZero" pUint32C 0
, NewFunEUI "countSucc" "inc" pUint32C 1 -}
]
where pBoolC _ = const $ return (TypeC "uint32_t")
pUintPtrC _ = const $ return (TypeC "uintptr_t")
pUint32C _ = const $ return (TypeC "uint32_t")
pVoidC _ = const $ return (TypeC "void")
pUnsignedC _ = const $ return (TypeC "unsigned")
pUndefTypeC _ _ = fail ""
pRetOfTypeC env x = case x of
Right (Apply _ [arg]) -> parseExprOfTypeC env arg
_ -> fail "pRetOfTypeC undefined"
pIOfTypeC env x = case x of
Right (Apply _ [arg]) -> parseExprOfTypeC env arg
_ -> fail "pIOfTypeC undefined"
pLLIOfTypeC env x = case x of
Left (Glob _ [arg]) -> parseTypeC env arg
_ -> fail "pLLIOfTypeC undefined"
------------------------ Parser ValC ----------------------------------------------------
pTrueValC nt env c@(ConstructorE _ []) = retValC "1" nt c env
pTrueValC _ _ _ = fail "pTrueValC undefined"
pFalseValC nt env c@(ConstructorE _ []) = retValC "0" nt c env
pFalseValC _ _ _ = fail "pFalseValC undefined"
pVoidValC nt env c@(ConstructorE _ []) = retValC "" nt c env
pVoidValC _ _ _ = fail "pVoidValC undefined"
pOValC nt env c@(ConstructorE _ []) = retValC "0" nt c env
pOValC _ _ _ = fail "pOValC undefined"
pSValC nt env (ConstructorE _ [p]) =
do res <- parseExprC env p
case res of
ValC (d, t) -> return $ ValC (show $ 1 + (read d :: Int), t)
expr -> do tC <- parseTypeC env tCoq
return $ BinOp (ValC ("1", tC)) "+" expr
where tCoq = Glob nt []
pSValC _ _ _ = fail "pSValC undefined"
envFunApply :: EnvUser -> EnvFunApply
envFunApply eu = EFA [ pRet
, pI
, parseOpBinOPC (envBinOp eu)
]
where pRet env (Apply (Global "Hardware.ret") [expr]) = parseExprC env expr
pRet _ _ = fail "pRet undefined"
pI env (Apply (Global "Parameters.i") [expr]) = parseExprC env expr
pI _ _ = fail "pI undefined"
envChangeName :: EnvUser -> EnvChangeName
envChangeName = foldr (\x y -> case x of { NewFunEUI nCoq nC _ _ -> [(nCoq, nC)]; _ -> []} ++ y) []
envBinOp :: EnvUser -> EnvBinOp
envBinOp = foldr (\x y -> case x of { OpBinEUI nCoq symb _ -> [(nCoq, symb)]; _ -> []} ++ y) []
envCondC :: EnvCondC
envCondC = EC [pPatOExprC, pPatTrueExprC, pPatFalseExprC, pPatSExprC]
envIncG :: ModuleUsed -> EnvUser -> MyEither EnvIncG
envIncG mu eu = toMyEith "envIncG construct undefined" body
where inclL = filter (\x -> case x of {IncludeListEUI{} -> True; _ -> False}) eu
body = includeListEUI <$> find ((mu ==) . nameModuleEUI) inclL
envType :: EnvUser -> EnvType
envType = foldr (\x y -> case x of
NewTypeEUI tCoq tC ev -> ETI tCoq tC : foldr (\(tCoq',_) y' -> ETI tCoq' tC : y') [] ev
OpBinEUI nCoq _ tC -> [ETI nCoq tC]
NewFunEUI nCoq _ tC n -> [ETI nCoq (f n tC)] -- TypeCFun tC
NewVarEUI _ _ -> []
_ -> []
--NewVarEUI nCoq (VarEmptyDecl (_, tC)) -> [retConstPType nCoq tC]
--NewVarEUI nCoq (VarDecl (_, tC) _) -> [retConstPType nCoq tC]
++ y) []
where f :: Int -> (EnvG -> Parser (Either Type Expr) TypeC) -> (EnvG -> Parser (Either Type Expr) TypeC)
f n p env e = TypeCFun . (replicate n (TypeC "") ++) . (:[]) <$> p env e
envValC :: EnvUser -> EnvValC
envValC = EVC . foldr (\x y -> case x of {NewTypeEUI nt _ ev -> map (\(n, f) -> (n, f nt) ) ev; _ -> []} ++ y) []
envVarC :: EnvUser -> EnvVarC
envVarC _ = []
envArgs :: OA.Parser EnvArgs
envArgs = EnvArgs <$> imports <*> gloincs <*> locincs <*> header <*> output <*> outputH <*> input
where input = strArgument $ metavar "INPUT.json"
<> help "Coq module (extracted as JSON) to compile into C code"
imports = many $ strOption $
short 'm'
<> long "module"
<> metavar "MODULE.json"
<> help "load function names and types from the given Coq MODULE (extracted as JSON)"
gloincs = many $ strOption $
short 'i'
<> long "include"
<> metavar "INCL.h"
<> help "add #include directive for this (global) header file"
locincs = many $ strOption $
short 'I'
<> long "locinclude"
<> metavar "INCL.h"
<> help "add #include directive for this local header file"
header = optional $ strOption $
long "header"
<> metavar "FILE"
<> help "add the content of FILE to the header of the generated C file"
output = optional $ strOption $
short 'o'
<> long "output"
<> metavar "FILE.c"
<> help "output extracted C code into FILE.c (defaults to INPUT.c)"
outputH = optional $ strOption $
short 'O'
<> long "output-h"
<> metavar "FILE.h"
<> help "output extracted C code headers into FILE.h"
envG :: EnvUser -> EnvG
envG eu = (envVarC eu, envType eu, envValC eu, envFunApply eu, envChangeName eu)
------------------------------------------
parseMacroTypeC :: Parser Type TypeC
parseMacroTypeC type' = TypeC <$> f type'
where f :: Parser Type String
f t = case t of
Glob n [] -> parseNameC n
Glob n (p:ps) -> do nm <- parseNameC n
p1 <- f p
pn <- concatMapM (\p' -> (", "++) <$> f p') ps
return $ nm ++ "(" ++ p1 ++ pn ++ ")"
_ -> fail "parseMacroTypeC undefined"
parseError :: ParseError -> String
parseError PE_NOT_IF_THEN_ELSE = "The pattern matching is not possible to parse in the conditionnal struct"
parseOpBinOPC :: EnvBinOp -> EnvG -> Parser Expr ExprC
parseOpBinOPC envb env (Apply (Global op) args) = if length args /= 2
then fail "parseOpBinOPC : Arguments > 2"
else do yop <- lookupEnvBinOp op envb
le <- parseExprC env (head args)
re <- parseExprC env (args !! 1)
return $ BinOp le yop re
parseOpBinOPC _ _ _ = fail "parseOpBinOPC undefined"
parseTypeC :: EnvG -> Parser Type TypeC
parseTypeC env tp = do r <- pType tp
return (if length r == 1
then head r
else TypeCFun r
)
where pType :: Parser Type [TypeC]
pType t = case t of
Varidx{} -> fail "Exception, error variable type"
Glob n _ -> (:[]) <$> (runParserEnvT n env (Left t) ||| parseMacroTypeC t)
Arrow l@Arrow{} r -> (:) <$> (TypeCFun <$> pType l) <*> pType r
Arrow l r -> (++) <$> pType l <*> pType r
parseNameC :: Parser NameCoq NameC
parseNameC nameCoq = if nameC == nameCoq'
then return nameC
else fail $ "parseNameC fail, the identifier is not correct : " ++ nameCoq
where nameCoq' = clearPref nameCoq
pattern' = "[a-zA-Z_](_?[a-zA-Z0-9]+)*" :: String
nameC = (nameCoq' =~ pattern') :: String
parseExprOfTypeC :: EnvG -> Parser Expr TypeC
parseExprOfTypeC env expr = case expr of
Rel name -> lookupEnvVar name env -- Regarde dans l'environnement des variables locales
Global name -> typeRetTypeC <$> runParserEnvT name env (Right expr) -- Regarde dans l'environnement des types
Apply (Global fname) _ -> typeRetTypeC <$> runParserEnvT fname env (Right expr) -- idem
Apply (Rel fname) _ -> typeRetTypeC <$> lookupEnvVar fname env -- idem
ConstructorE name _ -> runParserEnvT name env (Right expr) -- idem
_ -> fail "parseExprOfTypeC undefined" -- Echoue en renvoyant Nothing
parseDeclVarC :: EnvG -> Parser (Either Decl Expr) (EnvG, DeclVarC)
parseDeclVarC env decl = case decl of
Left (Term n t@Glob{} (Lambda _ e@ConstructorE{})) -> do typeV <- parseTypeC env t
expr <- parseExprC env e
n' <- parseNameC n
let var = (n', typeV)
return ( addTypeCEnvT env [retConstPType n' typeV]
, VarDecl var expr
)
Right (Let n expr _) -> do rvalue <- parseExprC env expr
lvalType <- parseExprOfTypeC env expr
if lvalType == typeVoid
then fail "Exception parseDeclVar, the type of rvalue is void"
else do n' <- parseNameC n
let var = VarDecl (n', lvalType) rvalue -- Pas de reference sur la variable
return (addVarsCEnvG env [var], var)
_ -> fail $ "parseDeclVarC undefined, decl : " ++ take debugRender (show decl)
parseDeclC :: EnvG -> Parser Decl [DeclC]
parseDeclC e decl = case decl of
Term{} -> (:[]) . VarCDecl . snd <$> parseDeclVarC e (Left decl) |||
(:[]) . FunDecl <$> parseFunctionC e decl
Fixgroup{} -> map FunDecl <$> parseFunctionCFX e decl
parseDeclH :: EnvG -> Parser Decl (EnvG, [DeclC])