-
Notifications
You must be signed in to change notification settings - Fork 5
/
grammar.py
1389 lines (1284 loc) · 48 KB
/
grammar.py
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
# Tampio Compiler
# Copyright (C) 2018 Iikka Hauhio
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from itertools import chain
from collections import namedtuple
from fatal_error import syntaxError
from inflect import *
from ast import *
from lex import accept, checkEof, eat, eatComma, eatPeriod, afterCommaThereIs, ADJ, NOUN, NAME, PRONOUN, NUMERAL, VERB, CONJ, CARDINALS, ORDINALS
def initializeParser():
global options, current_class
options = {
"kohdekoodi": False,
"takaisinviittaukset": False
}
current_class = None
POSTPOSITIONS = {
"nimento": ["kertaa"],
"omanto": [
"alla", "alta", "alle",
"keskellä", "keskeltä", "keskelle",
"edessä", "edestä", "eteen",
"takana", "takaa", "taakse",
"vieressä", "vierestä", "viereen",
"vierellä", "viereltä", "vierelle",
"luona", "luota", "luokse",
"lähellä", "läheltä", "lähelle",
"ohessa", "ohesta", "oheen",
"ohella", "ohelta", "ohelle",
"seassa", "seasta", "sekaan",
"sisällä", "sisältä", "sisälle",
"yllä", "yltä", "ylle",
"ali", "alitse",
"ohi", "ohitse",
"lomitse",
"läpi", "lävitse",
"poikki", "poikitse",
"yli", "ylitse",
"ympäri",
"mukaisesti", "mukaan",
"kanssa",
"suhteen",
"takia",
"kuluessa"
],
"osanto": [
"kohden", "kohti",
"vastaan",
"vasten",
"varten"
],
"sisatulento": [
"asti",
"mennessä",
"saakka"
]
}
FAKE_INTRANSITIVES = [
"ammuttu",
"halveksuttu",
"haukuttu",
"hyväksytty",
"kammoksuttu",
"kaduttu",
"kehuttu",
"kutsuttu",
"kysytty",
"lausuttu",
"lähestytty",
"manguttu",
"noiduttu",
"omaksuttu",
"oudoksuttu",
"paheksuttu",
"peruttu",
"puhuttu",
"riisuttu",
"uhkuttu",
"väheksytty",
"väijytty",
"yllätytty"
]
def isPartitiveIntransitiveParticiple(word):
return (word.isAdjective()
and word.form == "osanto"
and len(word.baseform) > 4 and word.baseform[-4:] in ["uttu", "ytty"]
and word.baseform not in FAKE_INTRANSITIVES)
def formToEnglish(form, article=True, short = False):
if short:
if form in CASES_ENGLISH:
return CASES_ENGLISH[form]
else:
return form
else:
if form in CASES_ENGLISH:
return "in " + CASES_ENGLISH[form] + " case"
elif form in chain.from_iterable(POSTPOSITIONS.values()):
return ("an " if article else "") + "argument to the " + form + " postposition"
else: # intransitive participle
return "an agent to the " + form + " participle"
def parseDeclaration(tokens):
global current_class
current_class = None
checkEof(tokens)
token = tokens.peek()
# Metodi, proseduuri
if token.token.lower() == "kun":
tokens.next()
tokens.setStyle("keyword")
signature = parseSentence(tokens, signature=True)
if isinstance(signature, MethodCallStatement):
current_class = signature.obj.type
with AllowBackreferences():
body = parseList(parseSentence, tokens, do_format=True)
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return ProcedureDecl(signature, body, stmts)
# Globaali muuttuja
elif token.token.lower() == "olkoon":
tokens.next()
tokens.setStyle("keyword")
word1, word2 = parseVariable(tokens, case="nimento")
value = parseNominativePredicative(tokens)
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return VariableDecl(word1.baseform + "_" + word2.baseform, word2.baseform, value, stmts)
# Imperatiivit
elif token.token.lower() == "sisällytä":
tokens.next()
tokens.setStyle("keyword")
if options["kohdekoodi"] and tokens.peek() and tokens.peek().token.lower() == "kohdekoodi":
tokens.next()
tokens.setStyle("keyword")
code = tokens.next()
if not code.isString():
syntaxError("target code is not a string token", tokens)
tokens.setStyle("literal")
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return TargetCodeDecl(parseString(code.token), stmts)
elif tokens.peek() and tokens.peek().token.lower() in ["tiedosto"]+(["kohdekooditiedosto"] if options["kohdekoodi"] else []):
tc = tokens.next().token.lower() == "kohdekooditiedosto"
tokens.setStyle("keyword")
filename = tokens.next()
if not filename.isString():
syntaxError("file name is not a string token", tokens)
tokens.setStyle("literal")
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
if not tc:
return IncludeFileDecl(parseString(filename.token), stmts)
else:
return IncludeTargetCodeFileDecl(parseString(filename.token), stmts)
elif token.token.lower() in ["salli", "kiellä"]:
positive = tokens.next().token.lower() == "salli"
tokens.setStyle("keyword")
if tokens.peek() and tokens.peek().isWord():
option = tokens.next().token.lower()
tokens.setStyle("literal")
options[option] = positive
eatPeriod(tokens)
tokens.addNewline()
return SetOptionDecl(positive, option)
elif token.token.lower() == "tulkitse":
tokens.next()
tokens.setStyle("keyword")
cl = tokens.next().toWord(cls=NOUN,forms="nimento")
if cl.form != "nimento":
syntaxError("class name not in the nominative case", tokens)
tokens.setStyle("type")
if (options["kohdekoodi"]
and tokens.peek() and tokens.peek().token.lower() == "kohdekoodityyppinä"
and tokens.peek(2) and tokens.peek(2).isString()):
tokens.next()
tokens.setStyle("keyword")
tc_class = parseString(tokens.next().token)
tokens.setStyle("literal")
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return TargetCodeClassDecl(cl.baseform, tc_class, stmts)
else:
cl2 = tokens.next().toWord(cls=NOUN,forms="olento")
if cl2.form != "olento":
syntaxError("class name not in the essive case", tokens)
tokens.setStyle("type")
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return AliasClassDecl(cl.baseform, cl2.baseform, stmts)
# Vertailuoperaattori
elif afterCommaThereIs("jos", tokens):
varname, typename, case = parseSelfVariable(tokens)
signature = parseConditionPredicateAndArgs(tokens, VariableExpr(varname, typename), case, allow_negation=False)
accept([","], tokens)
accept(["jos"], tokens)
tokens.setStyle("keyword")
conditions = parseOuterCondition(tokens, do_format=True)
wheres = parseWheres(tokens)
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return CondFunctionDecl(typename, signature, conditions, wheres, stmts)
# Muut
else:
word = token.toWord(cls=NOUN+ADJ,forms=["ulkoolento", "omanto", "nimento"])
# Luokka
if word.isNoun() and word.form == "ulkoolento":
tokens.next()
tokens.setStyle("type")
kw = accept(["on", "ei"], tokens)
tokens.setStyle("keyword")
if kw == "on":
fields = parseList(parseFieldDecl, tokens)
else:
accept(["ole"], tokens)
tokens.setStyle("keyword")
accept(["kenttiä"], tokens)
tokens.setStyle("keyword")
fields = []
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return ClassDecl(word.baseform, fields, stmts)
elif word.isNoun() or word.isAdjective():
varname, typename, case = parseSelfVariable(tokens, ["omanto", "nimento"])
current_class = typename
# Perivä luokka
if varname == "" and case == "nimento" and tokens.peek() and tokens.peek().token.lower() == "on":
tokens.next()
tokens.setStyle("keyword")
if word.form != "nimento":
syntaxError("class name not in the nominative case", tokens)
checkEof(tokens)
super_type = tokens.next().toWord(cls=NOUN,forms=["nimento"])
if not super_type.isNoun() or super_type.form != "nimento":
syntaxError("super type must be a noun in the nominative case", tokens)
if tokens.peek() and tokens.peek().token == ",":
tokens.next()
accept(["jolla"], tokens)
tokens.setStyle("keyword")
accept(["on"], tokens)
tokens.setStyle("keyword")
fields = parseList(parseFieldDecl, tokens)
else:
fields = []
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return ClassDecl(typename, fields, stmts, super_type=super_type.baseform)
# Funktio
elif case in ["omanto", "nimento"]:
place = tokens.place()
field, field_case, field_number, param, param_case = parseFieldName(tokens, word.form)
if field in ARI_OPERATORS and ARI_OPERATORS[field][0] == param_case:
tokens.setPlace(place)
tokens.next()
syntaxError("redefinition of builtin", tokens)
if (field_case == "nimento" and field_number == "plural") or (field_case == "olento" and word.number == "plural"):
accept(["ovat"], tokens)
else:
accept(["on"], tokens)
tokens.setStyle("keyword")
if tokens.peek().token.lower() == "pysyvästi":
tokens.next()
tokens.setStyle("keyword")
memoize = True
else:
memoize = False
body = parseNominativePredicative(tokens)
wheres = parseWheres(tokens)
stmts = parseAdditionalStatements(tokens)
eatPeriod(tokens)
tokens.addNewline()
return FunctionDecl(typename, field, varname, param, param_case, body, wheres, memoize, stmts)
tokens.next()
syntaxError("malformed declaration", tokens)
def parseSelfVariable(tokens, forms=[]):
word = tokens.next().toWord(cls=ADJ+NOUN,forms=forms)
if word.isAdjective():
tokens.setStyle("variable")
_, typeword = parseVariable(tokens, word=word, case="")
varname = word.baseform + "_" + typeword.baseform
elif word.isNoun():
typeword = word
tokens.setStyle("type")
varname = ""
else:
syntaxError("expected variable or type name", tokens)
return varname, typeword.baseform, typeword.form
def parseVariable(tokens, word=None, case="nimento"):
if not word:
checkEof(tokens)
word = tokens.next().toWord(cls=ADJ, forms=[case])
if not word.isAdjective() or (case and word.form != case):
syntaxError("this variable must begin with an adjective " + formToEnglish(case, article=False), tokens)
tokens.setStyle("variable")
checkEof(tokens)
word2 = tokens.next().toWord(cls=NOUN, forms=[word.form])
if not word2.isNoun() or (case and word2.form != case):
syntaxError("this variable must end with a noun " + formToEnglish(case, article=False), tokens)
if not word.agreesWith(word2):
syntaxError("variable words do not agree", tokens)
tokens.setStyle("type")
return word, word2
# predikatiivi voi olla joko nominaalilauseke tai yksi substantiivi (=new-lauseke)
# nominatiivisen merkkijonon edessä ei tarvitse olla substantiivia
def parsePredicative(tokens):
return parseNominalPhrase(tokens, promoted_cases=["nimento"], predicative=True)
def parseNominativePredicative(tokens, name="predicative"):
value, case = parsePredicative(tokens)
if case != "nimento":
syntaxError(name + " is " + formToEnglish(case) + " (should be in the nominative case)")
return value
INITIAL_VALUE_KEYWORDS = ["aluksi", "alussa", "yleensä"]
def parseFieldDecl(tokens):
field_name = parseFieldName(tokens)
if tokens.peek() and tokens.peek().token == "," and tokens.peek(2) and tokens.peek(2).token.lower() == ("jotka" if field_name[2] == "plural" else "joka"):
tokens.next()
tokens.next()
tokens.setStyle("keyword")
accept(["ovat" if field_name[2] == "plural" else "on"], tokens)
tokens.setStyle("keyword")
if eat(INITIAL_VALUE_KEYWORDS, tokens):
tokens.setStyle("keyword")
value = parseNominativePredicative(tokens)
eatComma(tokens)
return field_name + (value,)
elif field_name[2] == "plural" and tokens.peek() and tokens.peek().token == "," and tokens.peek(2) and tokens.peek(2).token.lower() == "joita":
tokens.next()
tokens.next()
tokens.setStyle("keyword")
accept(["ovat"], tokens)
tokens.setStyle("keyword")
if eat(INITIAL_VALUE_KEYWORDS, tokens):
tokens.setStyle("keyword")
value = ListExpr(parseList(parseNominativePredicative, tokens))
eatComma(tokens)
return field_name + (value,)
elif tokens.peek() and tokens.peek().token == "[":
tokens.next()
if eat(INITIAL_VALUE_KEYWORDS, tokens):
tokens.setStyle("keyword")
value = parseNominativePredicative(tokens)
accept("]", tokens)
return field_name + (value,)
else:
return field_name + (None,)
def parseFieldName(tokens, form="omanto"):
expected_form = "nimento" if form == "omanto" else "olento"
checkEof(tokens)
word = tokens.next().toWord(cls=NOUN,forms=[expected_form,"superlative"])
if word.form != expected_form:
syntaxError("malformed member name, expected a noun " + formToEnglish(expected_form, article=False), tokens)
tokens.setStyle("field")
field = word.baseform
# jäsennetään superlatiiviattribuutti
if word.isAdjective() and word.comparison == "superlative":
word2 = tokens.next().toWord(cls=NOUN,forms=[expected_form])
if word2.form != expected_form:
syntaxError("malformed member name, expected a noun " + formToEnglish(expected_form, article=False), tokens)
if word2.number != word.number:
syntaxError("malformed member name, the adjective and the noun do not agree in number", tokens)
tokens.setStyle("field", continued=True)
field += "_" + word2.baseform
word = word2
if word.form == "olento":
field += "_E"
# jäsennetään parametri
if tokens.peek() and tokens.peek().toWord(cls=VERB).isAdjective():
w1, w2 = parseVariable(tokens, case="")
return field, word.form, word.number, w1.baseform + "_" + w2.baseform, w1.form
return field, word.form, word.number, None, None
def parseWheres(tokens):
token = tokens.peek()
if token and token.token.lower() == "," and tokens.peek(2) and tokens.peek(2).token.lower() == "missä":
tokens.next()
tokens.next()
tokens.setStyle("keyword")
wheres = parseList(parseAssignment, tokens, do_format=True)
eatComma(tokens)
elif token and token.token.lower() == "missä":
if tokens.current().token != ",":
syntaxError("there must be a comma before \"missä\"", tokens)
tokens.next()
tokens.setStyle("keyword")
wheres = parseList(parseAssignment, tokens, do_format=True)
eatComma(tokens)
else:
wheres = []
return wheres
def parseAdditionalStatements(tokens):
ans = []
with AllowBackreferences():
while not tokens.eof() and tokens.peek().token == ";":
tokens.next()
ans += parseList(parseSentence, tokens, do_format=True)
return ans
# takaisinviittauksien sallija
class AllowBackreferences:
def __enter__(self):
global allow_backreferences
self.prev = allow_backreferences
allow_backreferences = options["takaisinviittaukset"]
def __exit__(self, *args):
global allow_backreferences
allow_backreferences = self.prev
allow_backreferences = False
# pino jokainen-lausekkeiden tallentamista varten (siis for-silmukoiden, vrt. rödan _)
FOR_STACK = []
ForVar = namedtuple("ForVar", ["name", "expr", "type"])
def pushFor(*allowed_types):
FOR_STACK.append((allowed_types, []))
def addForVar(i_name, expr, var_type, tokens):
if var_type == "mikään":
var_type = "jokainen"
if len(FOR_STACK) == 0 or var_type not in FOR_STACK[-1][0]:
syntaxError("\"" + var_type + "\" can't be used in this context", tokens)
name = i_name
i = 1
while [fv.name for fv in FOR_STACK[-1][1]].count(name) > 0:
name = i_name + str(i)
i += 1
FOR_STACK[-1][1].append(ForVar(name, expr, var_type))
return name
def popFor():
return FOR_STACK.pop()[1]
def parseSentence(tokens, signature=False):
checkEof(tokens)
token = tokens.peek()
if not signature and token.token.lower() == "jos" or (token.token == "," and tokens.peek(2) and tokens.peek(2).token.lower() == "jos"):
# varmistetaan, että ennen "jos"-sanaa on pilkku
if token.token == ",":
tokens.next()
elif tokens.current().token != ",":
syntaxError("there must be a comma before \"jos\"", tokens)
# parsitaan "jos"
tokens.next()
tokens.setStyle("keyword")
# parsitaan "jos taas" ja "jos kuitenkin" (else-lohko) TODO: entä jos tähän ei voi tulla else-lohkoa?
if tokens.peek().token.lower() in ["taas", "kuitenkin"]:
tokens.next()
tokens.setStyle("keyword")
is_else = True
else:
is_else = False
# parsitaan ehto
conditions = parseOuterCondition(tokens, False, ["niin"])
# ehdon saattaa päättää niin-sana
if tokens.peek().token.lower() == "niin":
tokens.next()
tokens.setStyle("keyword")
# parsitaan lohko
block = parseList(parseSentence, tokens, do_format=True)
eatComma(tokens)
return IfStatement(conditions, block, is_else)
pushFor("jokainen")
word = tokens.peek().toWord(
cls=ADJ*2+NUMERAL*2+NAME*2+VERB,
forms=["imperative_present_simple2", "indicative_present_simple4", "nimento", "osanto"])
if word.isVerb():
tokens.next()
tokens.setStyle("function")
place = tokens.place()
for_vars = popFor()
subjectless = True
passive = True
if word.form == "imperative_present_simple2":
predicate = word.baseform + "!"
elif word.form == "indicative_present_simple4":
predicate = word.baseform + readVerbModifiers(tokens)
else:
syntaxError("predicate ("+word.word+") is not in indicative or imperative simple present", tokens, place)
else:
subject, case = parseNominalPhrase(tokens, promoted_cases=["nimento", "omanto"])
if signature and not isinstance(subject, VariableExpr):
syntaxError("malformed parameter", tokens)
place = tokens.place()
for_vars = popFor()
checkEof(tokens)
word = tokens.next().toWord(
cls=VERB,
forms=["indicative_present_simple3", "indicative_present_simple4", "E-infinitive_sisaolento"])
if word.isVerb() and word.form in ["E-infinitive_sisaolento3", "E-infinitive_sisaolento4"]:
tokens.setStyle("function")
method = word.baseform + readVerbModifiers(tokens)
if word.form[-1] == "3":
method += "_A"
else:
method += "_P"
if word.form[-1] == "3" and case != "omanto":
syntaxError("subject is not in the genitive case", tokens, place)
subject_case = "nimento" if word.form[-1] == "3" else case
params = {}
while not tokens.eof():
peek = tokens.peek()
if peek.token.lower() == "käyköön":
break
if not peek.isWord() or not peek.toWord(cls=ADJ).isAdjective():
break
param, case = parseNominalPhrase(tokens)
if not isinstance(param, VariableExpr):
syntaxError("malformed parameter", tokens)
if case in params:
syntaxError("parameter repeated twice", tokens)
params[case] = param
for keyword in ["käyköön", "niin", ",", "että"]:
accept([keyword], tokens)
if keyword != ",":
tokens.setStyle("keyword")
body = parseList(parseSentence, tokens, do_format=True)
eatComma(tokens)
stmt = MethodAssignmentStatement(subject, subject_case, method, params, body)
for for_var in reversed(for_vars):
stmt = ForStatement(for_var.name, for_var.expr, stmt)
return stmt
predicate, passive = parsePredicate(word, tokens, case)
subjectless = False
subject_case = case
for_var_list = []
args_list = []
output_vars = []
prev_args = {}
while True:
pushFor("jokainen")
args, ov = parseArgs(tokens, passive, predicate=="olla_A", signature=signature)
args_list.append({**prev_args, **args})
prev_args = args
output_vars.append(ov)
for_var_list.append(for_vars+popFor())
if not signature and not tokens.eof() and tokens.peek().token.lower() == "sekä":
tokens.next()
tokens.setStyle("keyword")
continue
else:
break
if len(args_list) == 1:
async_block = parseAsyncBlock(tokens)
else:
async_block = []
eatComma(tokens)
wheres = parseWheres(tokens)
stmts = []
for args, output_var, for_vars in zip(args_list, output_vars, for_var_list):
if subjectless:
stmt = ProcedureCallStatement(predicate, args, output_var, async_block)
else:
stmt = MethodCallStatement(subject, subject_case, predicate, args, output_var, async_block)
for for_var in reversed(for_vars):
stmt = ForStatement(for_var.name, for_var.expr, stmt)
stmts.append(stmt)
if len(stmts) == 1 and len(wheres) == 0:
return stmts[0]
else:
return BlockStatement(stmts, wheres)
def parsePredicate(word, tokens, subject_case):
if not word.isVerb() or word.form not in ["indicative_present_simple3", "indicative_present_simple4"]:
syntaxError("predicate is not in indicative simple present 3rd active or passive", tokens)
tokens.setStyle("function")
passive = word.form[-1] == "4"
predicate = word.baseform + readVerbModifiers(tokens, word.baseform=="olla") + ("_P" if passive else "_A")
return predicate, passive
def nextIsValidVerbModifier(tokens, allow_adverbs=True, allow_verbs=True, disallow_nominative_noun=False):
token = tokens.peek()
if not token or not token.isWord():
return False
word = token.toWord(cls=NOMINAL_PHRASE_CLASS)
return ((word.isNoun()
and (not disallow_nominative_noun or word.form != "nimento")
and not canStartNominalPhrase(word, tokens)
and word.form != "olento")
or (allow_adverbs and word.isAdverb())
or (allow_verbs and word.isVerb() and "E-infinitive" not in word.form and "infinitive" in word.form))
def readVerbModifiers(tokens, is_be_verb=False):
ans = ""
while not tokens.eof():
if nextIsValidVerbModifier(tokens, disallow_nominative_noun=is_be_verb):
token = tokens.next()
tokens.setStyle("function", continued=True)
ans += "_" + token.token.lower()
else:
break
return ans
def parseArgs(tokens, passive, allow_predicatives, signature=False, allow_return_var=True):
args = {}
while not tokens.eof():
if tokens.peek().token.lower() in [",", ";", ".", "]", "eikä", "ja", "sekä", "tai", "taikka", "tuloksenaan"]:
break
arg, case = parsePredicative(tokens) if allow_predicatives else parseNominalPhrase(tokens)
if signature and not isinstance(arg, VariableExpr):
syntaxError("malformed parameter", tokens)
if case in args:
syntaxError(formToEnglish(case, short=True) + " argument repeated twice", tokens)
args[case] = arg
if isinstance(arg, LambdaExpr): # että-lohkot ovat lauseissa aina viimeisenä
break
if (allow_return_var and not tokens.eof() and (
(tokens.peek().token.lower() == "tuloksenaan" and not passive)
or (tokens.peek().token.lower() == "tuloksena" and passive)
)):
tokens.next()
tokens.setStyle("keyword")
w1, w2 = parseVariable(tokens)
return args, (w1.baseform + "_" + w2.baseform, w2.baseform)
else:
return args, None
def parseAsyncBlock(tokens):
ans = []
last = False
while not last and tokens.peek() and tokens.peek().token.lower() in [",", "ja"] and tokens.peek(2) and tokens.peek(2).token.lower() == "minkä":
if tokens.next().token.lower() == "ja":
tokens.setStyle("keyword")
last = True
place = tokens.place()
tokens.next() # minkä
tokens.setStyle("keyword")
method_name = "a_" + tokens.next().token.lower()
tokens.setStyle("field")
w1, w2 = parseVariable(tokens, case="")
parameter = w1.baseform + "_" + w2.baseform
word = tokens.next().toWord(cls=VERB,forms=["indicative_present_simple3", "indicative_present_simple4"])
predicate, passive = parsePredicate(word, tokens, w1.form)
args, ov = parseArgs(tokens, passive, predicate=="olla_A")
eatComma(tokens)
ans.append((method_name, parameter, w2.baseform, MethodCallStatement(VariableExpr(parameter, w2.baseform), w1.form, predicate, args, ov, [])))
if len(ans) > 1 and not last:
tokens.setPlace(place)
syntaxError("the last sentence in this list must be separated from the others by \"ja\"", tokens)
return ans
CMP_OPERATORS = {
"yhtä suuri kuin": "==",
"yhtäsuuri kuin": "==",
"yhtä kuin": "==",
"tasan": "==",
"sama kuin": "===",
"erisuuri kuin": "!=",
"pienempi kuin": "<",
"pienempi tai yhtä suuri kuin": "<=",
"pienempi tai yhtäsuuri kuin": "<=",
"enintään": "<=",
"suurempi kuin": ">",
"suurempi tai yhtä suuri kuin": ">=",
"suurempi tai yhtäsuuri kuin": ">=",
"vähintään": ">="
}
CMP_TREE = {}
for key in CMP_OPERATORS.keys():
words = key.split()
branch = CMP_TREE
for word in words[:-1]:
if word not in branch:
branch[word] = {}
branch = branch[word]
branch[words[-1]] = CMP_OPERATORS[key]
def parseOuterCondition(tokens, prefix=False, end_keyword=[], do_format=False):
if do_format:
tokens.increaseIndentLevel()
expr = parseInnerCondition(tokens, prefix, end_keyword)
while tokens.peek().token.lower() in ["sekä", "taikka"]:
if do_format:
tokens.addNewline()
op = "&&" if tokens.next().token.lower() == "sekä" else "||"
tokens.setStyle("keyword")
expr = CondConjunctionExpr(op, [expr, parseInnerCondition(tokens, prefix, end_keyword)])
if do_format:
tokens.decreaseIndentLevel()
expr.wheres = parseWheres(tokens)
eatComma(tokens)
return expr
def parseInnerCondition(tokens, prefix, custom_endings):
conds, op = parseList(lambda t: parseCondition(t, prefix), tokens, custom_endings+["sekä", "taikka"], custom_conjunctions=["ja", "tai"])
if len(conds) == 1:
return conds[0]
else:
return CondConjunctionExpr("&&" if op == "ja" else "||", conds)
def parseCondition(tokens, prefix=False):
pushFor("jokainen", "jokin")
predicate = None
verbIsOlla = None
if prefix:
checkEof(tokens)
if tokens.peek().token.lower() == "eikö":
tokens.next()
tokens.setStyle("keyword")
negation = True
else:
predicate, verbIsOlla = parseConditionPredicate(tokens, True, False)
negation = False
operand1, self_case = parseNominalPhrase(tokens, promoted_cases=["nimento"])
expr = parseConditionPredicateAndArgs(tokens, operand1, self_case, predicate=predicate, verbIsOlla=verbIsOlla, prefix=prefix, negation=prefix and negation)
for_vars = popFor()
for for_var in reversed(for_vars):
expr = QuantifierCondExpr(for_var.type, for_var.name, for_var.expr, expr)
return expr
def parseConditionPredicateAndArgs(tokens, operand1, self_case, predicate=None, verbIsOlla=None, prefix=False, negation=False, allow_negation=True):
if not prefix:
checkEof(tokens)
if allow_negation and tokens.peek().token.lower() == "ei":
tokens.next()
tokens.setStyle("keyword")
predicate, verbIsOlla = parseConditionPredicate(tokens, False, True)
negation = True
else:
predicate, verbIsOlla = parseConditionPredicate(tokens, False, False)
negation = False
elif negation:
predicate, verbIsOlla = parseConditionPredicate(tokens, True, True)
tokens.setStyle("keyword")
args = []
if verbIsOlla:
operator, requires_second_operand = parseOperator(tokens)
if requires_second_operand:
operand2, case = parseNominalPhrase(tokens, promoted_cases=[self_case])
if case != self_case:
syntaxError("predicative is in " +formToEnglish(case) + " (should be in " +formToEnglish(self_case)+ ")", tokens)
else:
operand2 = None
return CondOperatorExpr(negation, operator, operand1, operand2)
else:
args, _ = parseArgs(tokens, False, False, allow_return_var=False)
return CondFunctionExpr(negation, predicate, operand1, args)
def parseConditionPredicate(tokens, prefix, negative):
verb = tokens.next().toWord(cls=VERB,forms=["indicative_present_simple3", "indicative_present_simple4"])
if not negative:
if prefix and not verb.interrogative:
syntaxError("predicate does not contain the interrogative suffix \"-ko\"", tokens)
if verb.form not in ["indicative_present_simple3", "indicative_present_simple4"]:
syntaxError("predicative is not in indicative simple present 3rd person active or passive", tokens)
else:
if verb.form != "imperative_present_simple2":
syntaxError("predicative is not in negative form (imperative)", tokens)
passive = verb.form[-1] == "4"
verbIsOlla = verb.baseform == "olla"
predicate = verb.baseform
if verbIsOlla:
tokens.setStyle("keyword")
else:
tokens.setStyle("conditional-operator")
predicate += readVerbModifiers(tokens)
predicate += "_P" if passive else "_A"
return predicate, verbIsOlla
def parseOperator(tokens):
checkEof(tokens)
if tokens.peek().token.lower() in CMP_TREE.keys():
branch = CMP_TREE
while isinstance(branch, dict):
token = tokens.next().token.lower()
if token in branch:
branch = branch[token]
tokens.setStyle("keyword")
else:
syntaxError("unexpected token, expected " + " or ".join(["\"" + t + "\"" for t in branch.keys()]), tokens)
return branch, True
elif (tokens.peek().isWord()
and tokens.peek(2)
and tokens.peek().toWord(cls=ADJ).isAdjective()
and (not tokens.peek(2).isWord() or not tokens.peek(2).toWord(cls=NOUN).isNoun())):
word = tokens.next().toWord(cls=ADJ)
tokens.setStyle("conditional-operator")
if word.form != "nimento":
syntaxError("expected an adjective in the nominative case", tokens)
if word.comparison == "comparative":
accept(["kuin"], tokens)
tokens.setStyle("keyword")
return ".c_" + word.baseform, True
else:
return ".p_" + word.baseform, False
elif tokens.peek().isWord() and not nextStartsNominalPhrase(tokens):
word = tokens.next().token.lower()
tokens.setStyle("conditional-operator")
return ".p_" + word, False
else:
return "==", True
NOMINAL_PHRASE_CLASS = 2*ADJ+2*NUMERAL+2*CONJ+2*PRONOUN+NOUN
def nextStartsNominalPhrase(tokens):
if tokens.eof():
return False
peek = tokens.peek()
if not peek.isWord():
return False
word = peek.toWord(cls=NOMINAL_PHRASE_CLASS)
return canStartNominalPhrase(word, tokens)
def canStartNominalPhrase(word, tokens):
return ((word.isAdjective()
and tokens.peek(2) and tokens.peek(2).isWord()
and tokens.peek(2).toWord(cls=NOUN).isNoun() and tokens.peek(2).toWord(cls=NOUN,forms=word.form).agreesWith(word))
or word.isPronoun()
or word.isVariable()
or word.isOrdinal()
or word.isCardinal()
or re.fullmatch(r'\d+', word.baseform)
or (word.isNoun() and tokens.peek(2) and tokens.peek(2).isString())
or (word.isNoun() and tokens.peek(2) and tokens.peek(2).token == "," and tokens.peek(3) and tokens.peek(3).token.lower() == "jonka")
or word.word.lower() == "riippuen")
def parseNominalPhrase(tokens, must_be_in_genitive=False, promoted_cases=[], predicative=False):
checkEof(tokens)
if tokens.peek().token.lower() == "riippuen":
accept(["riippuen"], tokens)
tokens.setStyle("keyword")
accept(["siitä"], tokens)
tokens.setStyle("keyword")
accept([","], tokens)
conds = parseOuterCondition(tokens, True, ["joko"])
if tokens.peek().token.lower() == "joko":
tokens.next()
tokens.setStyle("keyword")
tokens.increaseIndentLevel()
alt1, case1 = parseNominalPhrase(tokens)
accept(["tai"], tokens)
tokens.addNewline()
tokens.setStyle("keyword")
alt2, case2 = parseNominalPhrase(tokens)
tokens.decreaseIndentLevel()
if case1 != case2:
syntaxError("both operands of \"tai\" must be in the same case", tokens)
return TernaryExpr(conds, alt1, alt2), case1
if predicative and tokens.peek().isString():
expr = StrExpr(parseString(tokens.next().token))
tokens.setStyle("literal")
case = "nimento"
else:
expr = None
case = None
word = tokens.next().toWord(cls=ADJ+NAME+NUMERAL+PRONOUN,forms=promoted_cases)
if expr:
pass
elif word.isVariable():
tokens.setStyle("variable")
expr = VariableExpr(word.baseform)
case = word.form
elif word.isNoun() and word.possessive == "" and word.form == "olento" and word.word != "tuloksena":
tokens.setStyle("field")
expr, case = parseNominalPhrase(tokens)
elif word.baseform in ["jokainen", "jokin", "mikään"]:
tokens.setStyle("keyword")
case = word.form
expr, case2 = parseNominalPhrase(tokens, case == "omanto")
if case != case2:
syntaxError("a quantifier and its nominal phrase must be in the same case", tokens)
name = addForVar(word.baseform, expr, word.baseform, tokens)
expr = VariableExpr(name)
elif word.isOrdinal():
tokens.setStyle("literal")
case = word.form
index = NumExpr(ORDINALS.index(word.baseform)+1)
expr, case2 = parseNominalPhrase(tokens, case == "omanto")
if case != case2:
syntaxError("an ordinal and its nominal phrase must be in the same case", tokens)
expr = SubscriptExpr(expr, index)
elif word.isCardinal():
tokens.setStyle("literal")
case = word.form
expr = NumExpr(CARDINALS.index(word.baseform))
elif re.fullmatch(r'\d+', word.baseform):
tokens.setStyle("literal")
if word.form in ["nimento", "osanto"] and nextIsValidVerbModifier(tokens, allow_adverbs=False, allow_verbs=False):
word2 = tokens.next().toWord(cls=NOUN)
tokens.setStyle("keyword")
if word.form == "nimento":
case = word2.form if word2.form != "osanto" else "nimento"
elif word.form == "osanto" and word2.form == "osanto":
case = "osanto"
else:
syntaxError("the unit should be in the partitive case", tokens)
else:
case = word.form
expr = NumExpr(int(word.baseform))
elif word.isNoun() and tokens.peek() and tokens.peek().isString():
tokens.setStyle("keyword")
case = word.form
expr = StrExpr(parseString(tokens.next().token))
tokens.setStyle("literal")
elif word.isName():
tokens.setStyle("variable")
case = word.form
variable = word.baseform
expr = VariableExpr(variable)
elif word.isPronoun() and word.baseform == "se":
if tokens.peek(1) and tokens.peek(1).token == "," and tokens.peek(2) and tokens.peek(2).token.lower() == "että":
tokens.setStyle("keyword")
accept([","], tokens)
accept(["että"], tokens)
tokens.setStyle("keyword")
with AllowBackreferences():
body = parseList(parseSentence, tokens, do_format=True)
eatComma(tokens)
case = word.form
expr = LambdaExpr(body)
elif (allow_backreferences and
nextIsValidVerbModifier(tokens, allow_adverbs=False, allow_verbs=False)
and tokens.peek().toWord(cls=NOUN,forms=word.form).agreesWith(word)): # takaisinviittaus edelliseen lausekkeeseen esim. "se olio"
tokens.setStyle("variable")
word2 = tokens.next().toWord(cls=NOUN,forms=word.form)
if word2.form == "omanto":
tokens.setStyle("variable-or-field")
case = "omanto"
expr = BackreferenceExpr(word2.baseform, may_be_field=True)
else:
tokens.setStyle("variable", continued=True)
case = word.form
expr = BackreferenceExpr(word2.baseform)
else:
tokens.setStyle("variable")
if tokens.peek() and tokens.peek().isWord():
word2 = tokens.peek().toWord(cls=PRONOUN)
if word2.baseform == "itse" and word2.agreesWith(word):
tokens.next()
tokens.setStyle("variable", continued=True)