forked from quil-lang/quilc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.lisp
1783 lines (1596 loc) · 76.4 KB
/
parser.lisp
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
;;;; src/parser.lisp
;;;;
;;;; Author: Robert Smith
(in-package #:cl-quil.frontend)
;;; There are three main steps on the journey from Quil string to Quil program,
;;; namely lexing, parsing, and analysis.
;;;
;;; The lexing rules are encoded in LINE-LEXER below, with TOKENIZE providing a
;;; higher interface with special management of indentation etc.
;;;
;;; Once lexed, the high-level control flow of parsing is managed by
;;; PARSE-PROGRAM-LINES, which dispatches on token type and hands off to
;;; specialized parsing routines.
;;;
;;; The main entry point provided here is PARSE-QUIL-INTO-RAW-PROGRAM. Most
;;; users would instead do well to use PARSE-QUIL, which performs additional
;;; analysis (like object resolution).
;;;
;;;
;;; A brief note on extensions:
;;;
;;; The parsing code below is written to support some amount of extensibility at
;;; runtime. There are two main hooks in for this:
;;;
;;; *LEXER-EXTENSIONS* allows for new keywords to be added
;;; *PARSER-EXTENSIONS* allows for new AST objects to be produced
;;;
;;; For more information on these mechanisms, see their respective documentation.
;;;;;;;;;;;;;;;;;;;;;;;;;; Lexical Analysis ;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype quil-keyword ()
'(member
:JUMP :JUMP-WHEN :JUMP-UNLESS :INCLUDE :MEASURE
:NEG :NOT :AND :IOR :XOR :MOVE :EXCHANGE :CONVERT :ADD :SUB :MUL :DIV
:LOAD :STORE :EQ :GT :GE :LT :LE :DEFGATE :DEFCIRCUIT :RESET
:HALT :WAIT :LABEL :NOP :CONTROLLED :DAGGER :FORKED
:DECLARE :SHARING :OFFSET :PRAGMA
:AS :MATRIX :PERMUTATION :PAULI-SUM :SEQUENCE))
(deftype token-type ()
'(or
quil-keyword
(member
:COLON :LEFT-PAREN :RIGHT-PAREN :COMMA :LABEL-NAME :PARAMETER
:STRING :INDENTATION :INDENT :DEDENT :COMPLEX :PLUS
:MINUS :TIMES :DIVIDE :EXPT :INTEGER :NAME :AREF)))
(defvar *line-start-position* nil)
(defvar *line-number* nil)
(defvar *current-file* nil
"The pathname for the file being currently parsed.")
(defstruct (token (:constructor tok (type &optional payload (line *line-number*) (pathname *current-file*))))
"A lexical token."
(line nil :type (or null (integer 1))
:read-only t)
(pathname nil :type (or null string pathname)
:read-only t)
(type nil :type symbol ; For vanilla Quil this will be
; TOKEN-TYPE, but for extensions the set
; of valid symbols may be larger.
:read-only t)
(payload nil :read-only t))
(defmethod print-object ((obj token) stream)
(print-unreadable-object (obj stream :type t :identity nil)
(format stream "~A~@[*~*~]~@[@L~D~]"
(token-type obj)
(token-payload obj)
(token-line obj))))
(defun parse-indent-string (str)
"Count the number of tabs/4-space indentations of the string STR."
(let* ((total-length (length str))
(tabs (count #\Tab str))
(spaces (- total-length tabs)))
(assert (zerop (mod spaces 4)))
(+ tabs (floor spaces 4))))
(defun parse-complex (real imag)
"Parse the complex number with real and imaginary components REAL, IMAG represented as NIL or strings."
(check-type real (or null string))
(check-type imag (or null string))
(flet ((parse-number (thing)
(declare (type (or null string) thing))
(if (null thing)
0.0d0
(parse-float thing :type 'double-float))))
(declare (inline parse-number))
(let ((re (parse-number real))
(im (parse-number imag)))
(declare (type double-float re im))
(if (zerop im)
re
(complex re im)))))
(defvar *lexer-extensions* '()
"A list of lexer extensions.
Each lexer extension is a function mapping strings to tokens. They are used to handle keywords in Quil language extensions.")
(defun match-lexer-extension (str)
"Given a string STR, check whether a lexer extension matches this string, and if so return the corresponding token."
(dolist (ext *lexer-extensions* nil)
(a:when-let ((kw (funcall ext str)))
(return-from match-lexer-extension kw))))
(alexa:define-string-lexer line-lexer
"A lexical analyzer for lines of Quil."
((:int "\\d+")
(:float "(?=\\d*[.eE])(?=\\.?\\d)\\d*\\.?\\d*(?:[eE][+-]?\\d+)?")
(:ident "[A-Za-z_](?:[A-Za-z0-9_\\-]*[A-Za-z0-9_])?")
(:string "\\\"(?:[^\\\"]|\\\\\\\")*\\\"")
(:newline "(?:\\r\\n?|\\n)"))
((eager "\\#[^\\n\\r]*")
nil)
((eager "{{NEWLINE}}")
;; We return a keyword because they get split out and
;; removed. They're not actually logical tokens of the Quil
;; language.
(incf *line-number*)
(setf *line-start-position* $>)
(return ':NEWLINE))
((eager "\\;")
(return ':SEMICOLON))
((eager "\\:")
(return (tok :COLON)))
((eager "\\(")
(return (tok :LEFT-PAREN)))
((eager "\\)")
(return (tok :RIGHT-PAREN)))
((eager "\\,")
(return (tok :COMMA)))
((eager "\\@({{IDENT}})")
(assert (not (null $1)))
(return (tok :LABEL-NAME (label $1))))
((eager "\\%({{IDENT}})")
(assert (not (null $1)))
(return (tok :PARAMETER (param $1))))
((eager "{{STRING}}")
(return (tok :STRING (read-from-string $@))))
((eager #.(string #-ccl #\DAGGER #+ccl #\u+2020))
(return (tok ':DAGGER)))
((eager #.(string #-ccl #\HELM_SYMBOL #+ccl #\u+2388))
(return (tok ':CONTROLLED)))
((eager #.(string #\OCR_FORK))
(return (tok ':FORKED)))
("INCLUDE|DEFCIRCUIT|DEFGATE|MEASURE|LABEL|WAIT|NOP|HALT|RESET|JUMP\\-WHEN|JUMP\\-UNLESS|JUMP|PRAGMA|NOT|AND|IOR|MOVE|EXCHANGE|SHARING|DECLARE|OFFSET|XOR|NEG|LOAD|STORE|CONVERT|ADD|SUB|MUL|DIV|EQ|GT|GE|LT|LE|CONTROLLED|DAGGER|FORKED|AS|MATRIX|PERMUTATION|PAULI-SUM|SEQUENCE"
(return (tok (intern $@ :keyword))))
((eager "(?<NAME>{{IDENT}})\\[(?<OFFSET>{{INT}})\\]")
(assert (not (null $NAME)))
(assert (not (null $OFFSET)))
(return (tok :AREF (cons $NAME (parse-integer $OFFSET)))))
((eager "\\[{{INT}}\\]")
(quil-parse-error "Old-style classical memory syntax, like ~A, isn't supported." $@))
("(?<NUM>{{FLOAT}})(?<IMAG>i)?"
(return
(if $IMAG
(tok :COMPLEX (constant (parse-complex nil $NUM)))
(tok :COMPLEX (constant (parse-complex $NUM nil))))))
("\\+" (return (tok :PLUS)))
("\\-" (return (tok :MINUS)))
("\\*" (return (tok :TIMES)))
("\\/" (return (tok :DIVIDE)))
("\\^" (return (tok :EXPT)))
("{{INT}}"
(return (tok :INTEGER (parse-integer $@))))
("{{IDENT}}"
(return
(cond
((string= "pi" $@) (tok :COMPLEX (constant pi)))
((string= "i" $@) (tok :COMPLEX (constant #C(0.0d0 1.0d0))))
(t (a:if-let ((kw (match-lexer-extension $@)))
kw
(tok :NAME $@))))))
((eager "(?: |\\t)+")
(when (= *line-start-position* $<)
(return (tok :INDENTATION (parse-indent-string $@)))))
;; Non-newline whitespace. In newer Perl, you can just use \h, for
;; "horizontal space", but this isn't supported in CL-PPCRE.
("[^\\S\\n\\r]+"
nil))
(defun tokenization-failure-context (input-string condition)
"Given an ALEXA:LEXER-MATCH-ERROR in CONDITION, return as multiple values the individual line and individual character within INPUT-STRING that triggered the condition."
(flet ((alexa-failure-position (condition)
;; This parses the error string of ALEXA, which looks like
;; "Couldn't find match at position 42 ...". This is
;; obviously a fragile and silly thing to do, so when ALEXA
;; is updated to have an error condition with direct access
;; to the failing position, update this code to suit.
(let* ((text (princ-to-string condition))
(start (position-if #'digit-char-p text)))
(parse-integer text :start start :junk-allowed t))))
(let* ((pos (alexa-failure-position condition))
(previous-newline (position #\Newline input-string
:end pos :from-end t))
(start (if previous-newline (1+ previous-newline) 0))
(end (position #\Newline input-string
:start pos)))
(values (subseq input-string start end)
(char input-string pos)))))
(defun tokenize-line (lexer string)
"Given a lexer (as defined by DEFINE-STRING-LEXER) and a string, return a list of tokens represented by that string."
(let ((*line-number* 1)
(*line-start-position* 0))
(handler-case
(let ((f (funcall lexer string)))
(loop :for tok := (funcall f)
:until (null tok)
:collect tok))
(alexa:lexer-match-error (c)
(multiple-value-bind (context-line failing-char)
(tokenization-failure-context string c)
(quil-parse-error "Unexpected input text ~S in ~S."
(string failing-char)
context-line))))))
(defun process-indentation (toks)
"Given a list of token lines TOKS, map all changes to :INDENTATION levels to :INDENT and :DEDENT tokens."
(let ((indent (tok :INDENT))
(dedent (tok :DEDENT)))
(labels ((indent (delta-level)
(cond
((zerop delta-level) nil)
((plusp delta-level) (make-list delta-level :initial-element indent))
((minusp delta-level) (make-list (abs delta-level) :initial-element dedent)))))
(loop :with new-toks := nil
:with level := 0
:for tok-line :in toks
:for type := (token-type (first tok-line))
:for payload := (token-payload (first tok-line))
:do (case type
((:INDENTATION)
(let ((delta (- payload level)))
(unless (endp (rest tok-line))
(push (append (indent delta) (rest tok-line)) new-toks)
(setf level payload))))
(otherwise
(push tok-line new-toks)))
:finally (return (nreverse new-toks))))))
(defun ensure-indentation (line)
(cond
((endp line) (list (tok ':INDENTATION 0)))
((eq ':INDENTATION (token-type (first line))) line)
(t (cons (tok ':INDENTATION 0) line))))
;;; SPLIT-SEQUENCE was too slow for 10k+ tokens.
(defun split-lines (tokens)
"Split TOKENS into non-empty sublists representing logical lines.
A logical line may be introduced either as the result of a :NEWLINE or a :SEMICOLON token. In the case of a :NEWLINE, the lines are split as written. In the case of :SEMICOLON, the following line is prefixed with the indentation of the immediately preceding line."
;; note: something like "H 0 ; X 1" will produce two lines for internal processing,
;; but the tokens themselves maintain their original line numbers for error reporting.
(declare (type list tokens)
(optimize speed (space 0)))
(let* ((pieces (cons nil nil))
(pieces-last pieces))
(declare (type cons pieces pieces-last))
(labels ((doit (start last end)
;; This was recursive, but it's been made iterative,
;; but we've kept the function around, just to minimize
;; change.
(declare (type list start last end))
(loop :when (null end)
;; Done
:do (unless (eq start end)
(rplacd pieces-last (cons start nil))
(setq pieces-last (cdr pieces-last))) ; unnec, but consistent
(return pieces)
:do
(cond
;; Split off a newline
((eq ':NEWLINE (car end))
(cond
((eq start end)
(let ((next (cdr start)))
(setq start next)
(setq last next)
(setq end next)))
(t
(rplacd pieces-last (cons start nil))
(setq pieces-last (cdr pieces-last))
(setq start (cdr end))
(rplacd last nil)
(setq last start)
(setq end start))))
;; A semicolon also results in a new line being split, but we
;; also inherit the preceding indentation.
((eq ':SEMICOLON (car end))
(cond
((eq start end)
(let ((next (cdr start)))
(setq start next)
(setq last next)
(setq end next)))
(t
(rplacd pieces-last (cons start nil))
(setq pieces-last (cdr pieces-last))
;; Prepend appropriate indentation
(setq start (if (eq ':INDENTATION (token-type (car start)))
(cons (car start) ; Copy the indentation (line number on this token is irrelevant)
(cdr end))
(cdr end)))
(rplacd last nil)
(setq last start)
(setq end start))))
;; Keep on truckin'.
(t
(setq last end)
(setq end (cdr end)))))))
(cdr (doit tokens tokens tokens)))))
(defun tokenize (string)
"Tokenize the Quil string STRING into a list of token lines with indentation resolved. Each token line is itself a list of tokens."
(let* ((lines (split-lines (tokenize-line 'line-lexer string))))
(map-into lines #'ensure-indentation lines)
(process-indentation lines)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Parser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-condition quil-parse-error (a:simple-parse-error)
()
(:documentation "Representation of an error parsing Quil."))
(define-condition quil-parse-error-at-line (quil-parse-error)
((line :initarg :line :reader line-of-quil-parse-error)
(pathname :initarg :pathname :reader pathname-of-quil-parse-error))
(:report (lambda (condition stream)
(format stream "At line ~D~@[ (~A)~]: "
(line-of-quil-parse-error condition)
(pathname-of-quil-parse-error condition))
(apply #'format stream (simple-condition-format-control condition)
(simple-condition-format-arguments condition)))))
(defun quil-parse-error (format-control &rest format-args)
"Signal a QUIL-PARSE-ERROR with a descriptive error message described by FORMAT-CONTROL and FORMAT-ARGS."
;; There are callers of this function where *line-number* is not set
;; appropriately (e.g. in expand-circuits.lisp) and where it may be impossible
;; to set due to missing context. Most callers of this function however are
;; right here in parser.lisp where *line-number* is more than likely set.
(if *line-number*
(error 'quil-parse-error-at-line :line *line-number*
:pathname *current-file*
:format-control format-control
:format-arguments format-args)
(error 'quil-parse-error :format-control format-control
:format-arguments format-args)))
(defvar *definitions-allowed* t
"Dynamic variable to control whether DEF* forms are allowed in the current parsing context.")
(defvar *formal-arguments-allowed* nil
"Dynamic variable to control whether formal parameters and arguments are allowed in the current parsing context.")
(defvar *parse-context*)
(setf (documentation '*parse-context* 'variable)
"A Quil keyword (e.g. :DEFGATE) indicating the context in which a portion of a Quil instruction is being parsed.")
(defun disappointing-token-error (found-token expected-msg)
(quil-parse-error "Expected ~A~@[ in ~A~], but observed a token ~A with value ~A."
expected-msg
*parse-context*
(token-type found-token)
(token-payload found-token)))
(defvar *parser-extensions* '()
"A list of parsers which may be invoked when PARSE-PROGRAM-LINES encounters tokens beyond vanilla Quil.
Each parser is a function mapping a list of lines of tokens to a pair,
1. The next AST object.
2. A list of lines that remain unparsed.
If the parser does not match, then it should return NIL.")
(defun match-parser-extension (tok-lines)
"Apply any parsers defined in *PARSER-EXTENSIONS* to the list of lines of tokens, TOK-LINES."
(dolist (parser *parser-extensions* (values nil tok-lines))
(multiple-value-bind (obj rest-lines)
(funcall parser tok-lines)
(when obj
(return-from match-parser-extension (values obj rest-lines))))))
(defun parse-program-lines (tok-lines)
"Parse the next AST object from the list of token lists. Returns two values:
1. The next AST object.
2. A list of lines that remain unparsed."
(let* ((line (first tok-lines))
(tok (first line))
(tok-type (token-type tok))
(*parse-context* tok-type)
(*line-number* (token-line tok)))
(case tok-type
;; Gate/Circuit Applications
((:CONTROLLED :DAGGER :FORKED)
(parse-modified-application tok-lines))
((:NAME)
(parse-application tok-lines))
;; Circuit Definition
((:DEFCIRCUIT)
(unless *definitions-allowed*
(quil-parse-error "Found DEFCIRCUIT where it's not allowed."))
(let ((*definitions-allowed* nil)
(*formal-arguments-allowed* t))
(parse-circuit-definition tok-lines)))
;; Gate Definition
((:DEFGATE)
(unless *definitions-allowed*
(quil-parse-error "Found DEFGATE where it's not allowed."))
(let ((*definitions-allowed* nil)
(*formal-arguments-allowed* t))
(parse-gate-definition tok-lines)))
;; Memory Declaration
((:DECLARE)
(unless *definitions-allowed*
(quil-parse-error "Found DECLARE where it's not allowed."))
(let ((*formal-arguments-allowed* t))
(parse-memory-descriptor tok-lines)))
;; Pragma
((:PRAGMA)
(parse-pragma tok-lines))
;; Measurement
((:MEASURE)
(parse-measurement tok-lines))
;; Halt, No-op, Wait
((:HALT :NOP :WAIT)
(parse-simple-instruction (token-type tok) tok-lines))
((:RESET)
(parse-reset-instruction tok-lines))
;; Include
((:INCLUDE)
(parse-include tok-lines))
;; Label
((:LABEL)
(parse-label tok-lines))
;; Jump
((:JUMP)
(parse-jump tok-lines))
;; Conditional Jump
((:JUMP-WHEN :JUMP-UNLESS)
(parse-conditional-jump tok-type tok-lines))
;; Unary classical function
((:NEG :NOT)
(parse-unary-classical tok-type tok-lines))
;; Binary classical function
((:AND :IOR :XOR :MOVE :EXCHANGE :CONVERT :ADD :SUB :MUL :DIV)
(parse-binary-classical tok-type tok-lines))
;; Trinary classical function
((:LOAD :STORE :EQ :GT :GE :LT :LE)
(parse-trinary-classical tok-type tok-lines))
(otherwise
(multiple-value-bind (obj rest-lines)
(match-parser-extension tok-lines)
(if obj
(values obj rest-lines)
(quil-parse-error "Got an unexpected token of type ~S ~
when trying to parse a program." tok-type)))))))
;; Many instructions are given by a single line of a few tokens. The
;; MATCH-LINE macro below just captures some boilerplate common to the
;; parsing of such instructions (namely, checking that there are the right
;; number and type of tokens, destructuring the corresponding token list,
;; and returning a result along with the rest of the lines.
(defmacro match-line (token-specs lines &body body)
"Bind the tokens in the first line of LINES according to the specified TOKEN-SPECS. These bindings are made available in the BODY.
A TOKEN-SPEC looks like a lambda list. There is support for three sorts of bindings: required, optional, and rest. If specializers (for required) or default values (for optional) are provided, these symbols are used to enforce a given token type.
For example, the spec ((op :RESET) &optional q) would match a single RESET token, or a RESET token followed by a second token.
In accordance with the typical usage here, there are two values returned: the result of BODY, and the (possibly null) list of remaining lines.
"
(let ((all-lines (gensym))
(first-line (gensym)))
(flet ((token-typecheck-clause (spec opt)
(when (listp spec)
(let ((spec-name (first spec))
(spec-type (second spec)))
(when spec-type
`((unless
,(if opt
`(or (null ,spec-name)
(eql ',spec-type (token-type ,spec-name)))
`(eql ,spec-type (token-type ,spec-name)))
(quil-parse-error
,(if (keywordp spec-type) ; If possible, format at expansion time.
(format nil "Expected ~S token, but got ~~S." spec-type)
`(format nil "Expected ~S token, but got ~~S." ,spec-type))
(token-type ,spec-name)))))))))
(multiple-value-bind (required optional rest)
(a:parse-ordinary-lambda-list token-specs
:allow-specializers t)
(let ((stripped-lambda-list (mapcar #'a:ensure-car
token-specs))
(first-type (second (first required))))
`(let ((,all-lines ,lines))
;; Check that we have a line to consume
(when (endp ,all-lines)
(quil-parse-error "Unexpectedly reached end of program~@[ (expected ~A instruction)~]." ,first-type))
(let ((,first-line (first ,all-lines)))
;; Check that we have the right number of tokens
,(let ((min-tokens (length required))
(max-tokens (unless rest
(+ (length required) (length optional)))))
`(unless (<= ,min-tokens
(length ,first-line)
. ,(when max-tokens (list max-tokens)))
(quil-parse-error "Expected at least ~A ~@[ and at most ~A~] tokens~@[ for instruction ~A~]."
,min-tokens
,max-tokens
,first-type)))
(destructuring-bind ,stripped-lambda-list ,first-line
;; Check the various token types
,@(mapcan (lambda (s) (token-typecheck-clause s nil))
required)
,@(mapcan (lambda (s) (token-typecheck-clause s t))
optional)
(values (progn ,@body)
(rest ,all-lines))))))))))
(defun parse-qubit (qubit-tok)
"Parse a qubit, denoted by a formal argument or an integer index."
(case (token-type qubit-tok)
((:NAME)
(unless *formal-arguments-allowed*
(quil-parse-error "Unexpected formal argument \"~A\"~@[ in ~A~]."
(token-payload qubit-tok)
*parse-context*))
(formal (token-payload qubit-tok)))
((:INTEGER) (qubit (token-payload qubit-tok)))
(otherwise
(disappointing-token-error qubit-tok
(if *formal-arguments-allowed*
"a name or formal argument"
"a name")))))
(defun parse-memory-or-formal-token (tok &key (ensure-valid t))
"Parse the token TOK as a memory reference or formal argument.
If ENSURE-VALID is T (default), then a memory reference such as 'foo[0]' will result in an error unless 'foo' has been DECLAREd."
(declare (special *memory-region-names*)) ; Forward declaration
(cond
;; Actual address to measure into.
((eql ':AREF (token-type tok))
(when (and ensure-valid
(not (find (car (token-payload tok)) *memory-region-names* :test #'string=)))
(quil-parse-error "Bad memory region name \"~A\"~@[ in ~A~]. This is probably due to either:
* a missing DECLARE for this memory,
* a misspelling of the memory reference, or
* a misspelling of the DECLAREd memory."
(car (token-payload tok))
*parse-context*))
(mref (car (token-payload tok))
(cdr (token-payload tok))))
;; Implicit address to measure into.
((and (eql ':NAME (token-type tok))
(find (token-payload tok) *memory-region-names* :test #'string=))
(mref (token-payload tok) 0))
;; Formal argument.
((eql ':NAME (token-type tok))
(unless *formal-arguments-allowed*
(quil-parse-error "Found formal argument \"~A\"~@[ in ~A~]."
(token-payload tok)
*parse-context*))
(formal (token-payload tok)))
(t
(disappointing-token-error tok
(if *formal-arguments-allowed*
"an address or formal argument"
"an address")))))
(defun parse-simple-instruction (type tok-lines)
(match-line ((op type)) tok-lines
(ecase type
((:HALT) (make-instance 'halt))
((:RESET) (make-instance 'reset))
((:NOP) (make-instance 'no-operation))
((:WAIT) (make-instance 'wait)))))
(defun parse-reset-instruction (tok-lines)
"Parse either a 'RESET' or 'RESET <q>' instruction where <q> is a :NAME or :INTEGER into a RESET or RESET-QUBIT instruction, respectively."
(match-line ((op :RESET) &optional q) tok-lines
(if (null q)
;; global RESET
(make-instance 'reset)
;; targeted RESET
(make-instance 'reset-qubit :target (parse-qubit q)))))
(defun take-until (f list)
"Take elements of LIST until the boolean function F is satisfied. More specifically, split LIST into two lists A and B (as two values) such that
* (append A B) is equal to LIST
* (notany f A) => T
* B is NIL, or (funcall f (first B)) => T.
"
(let ((head nil))
(loop :named driver :do
(cond
((or (endp list)
(funcall f (first list)))
(return-from driver (values (nreverse head) list)))
(t
(push (pop list) head))))))
(defun take-while-from-end (f list)
"Same as TAKE-WHILE, but operates starting at the end of the list."
(let ((p (position-if f list :from-end t)))
(if (null p)
(values list nil)
(values (subseq list 0 p)
(subseq list p)))))
(defun parse-parameter (tok)
"Parse a token/number/parameter TOK intended to be a parameter."
(let ((type (token-type tok)))
(case type
((:PARAMETER)
(unless *formal-arguments-allowed*
(quil-parse-error "Found formal parameter~@[ in ~A~] where not allowed: ~S."
*parse-context*
(token-payload tok)))
(token-payload tok))
((:COMPLEX)
(token-payload tok))
((:INTEGER)
(constant (coerce (token-payload tok) 'double-float)))
(otherwise
(disappointing-token-error tok "a parameter")))))
(defun parse-formal (tok)
"Parse a token TOK into a formal argument."
(case (token-type tok)
((:NAME)
;; Sanity check that we are allowed to savor a formal.
(unless *formal-arguments-allowed*
(quil-parse-error "Unexpected formal argument A~@[ in ~A~]."
(token-payload tok)
*parse-context*))
(formal (token-payload tok)))
(otherwise
(disappointing-token-error tok "a formal"))))
(defun parse-argument (tok)
"Parse a token TOK intended to be an argument."
(declare (special *memory-region-names* *shadowing-formals*)) ; Forward declaration
(case (token-type tok)
((:NAME)
(let ((names-memory-region-p (find (token-payload tok)
*memory-region-names*
:test #'string=))
(shadowing-formal (find (token-payload tok)
*shadowing-formals*
:test #'string=
:key #'formal-name)))
(unless (or names-memory-region-p
*formal-arguments-allowed*)
(quil-parse-error "Unexpected formal argument ~A~@[ in ~A~]."
(token-payload tok)
*parse-context*))
(cond
((and *formal-arguments-allowed*
shadowing-formal)
shadowing-formal)
(names-memory-region-p (mref (token-payload tok) 0))
(t
(warn "In PARSE-ARGUMENT, a formal was parsed even ~
though it isn't known contextually.")
(formal (token-payload tok))))))
((:INTEGER)
(qubit (token-payload tok)))
((:COMPLEX)
(token-payload tok))
((:AREF)
(mref (car (token-payload tok))
(cdr (token-payload tok))))
(otherwise
(disappointing-token-error tok "an argument"))))
;; Dear reader:
;;
;; I must apologize to you in advance for a petty crime I've
;; committed. The following special variables make use of "spooky action at a
;; distance".
;;
;; * *arithmetic-parameters* is used in the arithmetic parser to collect
;; parameters encountered while parsing, and also act as a map from those
;; parameters to symbols generated.
;;
;; * *segment-encountered* is used to track whether an expression contains
;; compile-time-unevaluable classical memory references.
;;
;; * *memory-region-names* is used to store a list of allowable memory region
;; names, to distinguish references to them from other parameter types.
;;
;; Sorry.
;;
;; Regards,
;;
;; Robert (& Eric)
(defvar *arithmetic-parameters*)
(setf (documentation '*arithmetic-parameters* 'variable)
"A special variable to detect and collect the parameters found in an arithmetic expression when parsing. An alist mapping formal parameters to generated symbols.")
(defvar *segment-encountered*)
(setf (documentation '*segment-encountered* 'variable)
"A special variable to detect the presence of a segment address found in an arithmetic expression when parsing. A simple boolean.")
(defvar *memory-region-names*)
(setf (documentation '*memory-region-names* 'variable)
"A special variable to collect the names of declared memory regions.")
(defvar *shadowing-formals* nil
"A special variable which indicates formal parameters (as a list of FORMAL objects) which shadow memory names.")
(defun gate-modifier-token-p (tok)
(member (token-type tok) '(:CONTROLLED :DAGGER :FORKED)))
(defun apply-modifiers-to-operator (processed-modifiers base-operator)
(if (endp processed-modifiers)
base-operator
(destructuring-bind (modifier-name &rest modifier-args)
(first processed-modifiers)
(declare (ignore modifier-args))
(ecase modifier-name
(:CONTROLLED
(apply-modifiers-to-operator (rest processed-modifiers)
(controlled-operator base-operator)))
(:DAGGER
(apply-modifiers-to-operator (rest processed-modifiers)
(dagger-operator base-operator)))
(:FORKED
(apply-modifiers-to-operator (rest processed-modifiers)
(forked-operator base-operator)))))))
(defun parse-modified-application (tok-lines)
(multiple-value-bind (modifiers rest-line)
(take-until (complement #'gate-modifier-token-p) (pop tok-lines))
(multiple-value-bind (app rest-lines)
(parse-application (cons rest-line tok-lines))
;; It will be an unresolved application, but that's OK. We can
;; still parse it out.
(loop :for modifier :in modifiers
:collect (ecase (token-type modifier)
(:CONTROLLED (list ':CONTROLLED))
(:DAGGER (list ':DAGGER))
(:FORKED (list ':FORKED)))
:into processed-modifiers
:finally (progn
(setf (application-operator app)
(apply-modifiers-to-operator
(reverse processed-modifiers)
(application-operator app)))
(return (values app rest-lines)))))))
(defun parse-parameter-or-expression (toks)
"Parse a parameter, which may possibly be a compound arithmetic expression. Consumes all tokens given."
(if (and (= 1 (length toks))
(not (member (token-type (first toks)) '(:NAME :AREF))))
(parse-parameter (first toks))
(let ((*arithmetic-parameters* nil)
(*segment-encountered* nil))
(let ((result (parse-arithmetic-tokens toks :eval t)))
(cond
((and (null *arithmetic-parameters*)
(null *segment-encountered*))
(unless (numberp result)
(quil-parse-error "A parameter or arithmetic expression was expected~@[ in ~A~]. Got something of type ~S."
*parse-context*
(type-of result)))
(constant result))
((or *formal-arguments-allowed*
(and *segment-encountered*
(null *arithmetic-parameters*)))
(make-delayed-expression
(mapcar #'first *arithmetic-parameters*)
(mapcar #'second *arithmetic-parameters*)
result))
(t
(quil-parse-error "Formal parameters found in a place they're not allowed.")))))))
(defun parse-application (tok-lines)
"Parse a gate or circuit application out of the lines of tokens TOK-LINES, returning an UNRESOLVED-APPLICATION."
(match-line ((op :NAME) &rest rest-toks) tok-lines
(if (endp rest-toks)
(make-instance 'unresolved-application
:operator (named-operator (token-payload op)))
(multiple-value-bind (params args)
(parse-parameters rest-toks :allow-expressions t)
;; Parse out the rest of the arguments and return.
(make-instance 'unresolved-application
:operator (named-operator (token-payload op))
:parameters params
:arguments (mapcar #'parse-argument args))))))
(defun parse-measurement (tok-lines)
"Parse a measurement out of the lines of tokens TOK-LINES."
(match-line ((op :MEASURE) qubit-tok &optional address-tok) tok-lines
(let ((qubit (parse-qubit qubit-tok)))
(if (null address-tok)
(make-instance 'measure-discard :qubit qubit)
(make-instance 'measure
:qubit qubit
:address (parse-memory-or-formal-token address-tok))))))
(defun parse-pragma (tok-lines)
"Parse a PRAGMA out of the lines of tokens TOK-LINES."
(match-line ((op :PRAGMA) (word-tok :NAME) &rest word-toks) tok-lines
(multiple-value-bind (words non-words)
(take-until (lambda (tok) (not (member (token-type tok) '(:NAME :INTEGER)))) (cons word-tok word-toks))
(setf words (mapcar #'token-payload words))
(cond
((null non-words)
(make-pragma words))
((endp (cdr non-words))
(let ((last-tok (first non-words)))
(unless (eql ':STRING (token-type last-tok))
(disappointing-token-error last-tok "a terminating string"))
(make-pragma words (token-payload last-tok))))
(t
(quil-parse-error "Unexpected tokens near the end of a PRAGMA."))))))
(defun parse-include (tok-lines)
"Parse an INCLUDE out of the lines of tokens TOK-LINES."
(match-line ((op :INCLUDE) (path :STRING)) tok-lines
(make-instance 'include :pathname (token-payload path))))
(defun validate-gate-matrix-size (gate-name num-entries)
"For the gate named GATE-NAME, check that NUM-ENTRIES is a valid number of entries for a gate matrix."
(unless (<= 4 num-entries)
(quil-parse-error "There must be at least 4 entries (a one-qubit ~
operator) for the gate ~A being defined. Got ~D."
gate-name
num-entries))
(unless (perfect-square-p num-entries)
(quil-parse-error "The number of entries of the gate ~A being defined ~
must be a perfect square (i.e., it must be a square ~
matrix. I got ~D entries."
gate-name
num-entries))
(unless (positive-power-of-two-p (isqrt num-entries))
(quil-parse-error "The gate ~A being defined isn't a square 2^n x 2^n ~
matrix. In particular, it is a ~D x ~D matrix."
gate-name
(isqrt num-entries)
(isqrt num-entries)))
t)
(defun parse-gate-definition (tok-lines)
"Parse a gate definition from the token lines TOK-LINES."
;; Check that we have tokens left
(when (null tok-lines)
(quil-parse-error "EOF reached when gate definition expected"))
;; Get the parameter and body lines
(let (name
(gate-type ':MATRIX))
(destructuring-bind (parameter-line &rest body-lines) tok-lines
(destructuring-bind (op . params-args) parameter-line
;; Check that we are dealing with a DEFGATE.
(unless (eql ':DEFGATE (token-type op))
(quil-parse-error "DEFGATE expected. Got ~S."
(token-type op)))
;; Check that something is following the DEFGATE.
(when (null params-args)
(quil-parse-error "Expected more after DEFGATE token."))
;; Check for a name.
(unless (eql ':NAME (token-type (first params-args)))
(disappointing-token-error (first params-args) "a name"))
;; We have a name. Stash it away.
(setf name (token-payload (pop params-args)))
(multiple-value-bind (params rest-line) (parse-parameters params-args)
(multiple-value-bind (args rest-line) (parse-arguments rest-line)
(when (eql ':AS (token-type (first rest-line)))
(pop rest-line)
(let* ((parsed-gate-tok (first rest-line))
(parsed-gate-type (token-type parsed-gate-tok)))
(unless (find parsed-gate-type '(:MATRIX :PERMUTATION :PAULI-SUM :SEQUENCE))
(quil-parse-error "Found unexpected gate type: ~A." (token-payload parsed-gate-tok)))
(setf gate-type parsed-gate-type)))
(ecase gate-type
(:MATRIX
(when args
(quil-parse-error "DEFGATE AS MATRIX cannot carry formal qubit arguments."))
(parse-gate-entries-as-matrix body-lines params name :lexical-context op))
(:PERMUTATION
(when args
(quil-parse-error "DEFGATE AS PERMUTATION cannot carry formal qubit arguments."))
(when params
(quil-parse-error "Permutation gate definitions do not support parameters."))
(parse-gate-entries-as-permutation body-lines name :lexical-context op))
(:PAULI-SUM
(let ((*shadowing-formals* args))
(parse-gate-definition-body-into-pauli-sum body-lines name
:lexical-context op
:legal-arguments args
:legal-parameters params)))
(:SEQUENCE
(let ((*shadowing-formals* args))
(parse-gate-definition-body-into-sequence body-lines name args params :context op))))))))))
(defun parse-gate-definition-body-into-sequence (body-lines name args params &key context)
(multiple-value-bind (parsed-body rest-lines)
(parse-indented-body body-lines)
(values (make-instance 'sequence-gate-definition
:name name
:parameters params
:arguments args
:sequence parsed-body
:context context)
rest-lines)))
(defun parse-gate-definition-body-into-pauli-sum (body-lines name &key lexical-context legal-arguments legal-parameters)
;; is the immediate next line indented? if not, error.
(let ((*segment-encountered* nil)
(*arithmetic-parameters* nil))
(multiple-value-bind (indented? modified-line)
(indented-line (first body-lines))
(unless indented?
(quil-parse-error "Declaration DEFGATE ~a ... AS PAULI-SUM has empty body."
name))
;; strip off the indentation.
(setf body-lines (list* modified-line (rest body-lines)))
;; otherwise, iterate til we hit a dedent token.
(loop :with parsed-entries := nil
:with remaining-lines := nil ; If there's no dedent, this
; will remain empty
:for line :in body-lines
:for rest-lines := (rest body-lines) :then (rest rest-lines)
:do (multiple-value-bind (dedented? modified-line)
(dedented-line-p line)
;; if we're done, return the gate definition (and
;; the rest of the lines)
(when dedented?
(setf remaining-lines (cons modified-line rest-lines))
(loop-finish))
;; store this word/qubits pair as part of the gate
;; definition
(push (parse-pauli-sum-line line
:lexical-context lexical-context
:legal-parameters legal-parameters
:legal-arguments legal-arguments)
parsed-entries))
:finally (return
(values (make-instance 'exp-pauli-sum-gate-definition
:name name
:terms (nreverse parsed-entries)
:context lexical-context
:arguments legal-arguments
:parameters (mapcar (lambda (p)
(or (cadr (assoc p *arithmetic-parameters* :test #'equalp))
(make-symbol (format nil "~a-UNUSED" (param-name p)))))
legal-parameters))
remaining-lines))))))
(defun parse-pauli-sum-line (line &key lexical-context legal-arguments legal-parameters)
"Parses a line inside of a DEFGATE ... AS PAULI-SUM body."
(declare (ignore lexical-context legal-parameters))
(let (pauli-word param qubit-list)