Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Αdding support for Q# language #2804

Merged
merged 21 commits into from
Mar 23, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion components.js

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions components.json
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,12 @@
"alias": "py",
"owner": "multipetros"
},
"qsharp": {
"title": "Q#",
"require": "clike",
"alias": "qs",
"owner": "fedonman"
},
"q": {
"title": "Q (kdb+ database)",
"owner": "Golmote"
Expand Down
168 changes: 168 additions & 0 deletions components/prism-qsharp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
(function (Prism) {

/**
* Replaces all placeholders "<<n>>" of given pattern with the n-th replacement (zero based).
*
* Note: This is a simple text based replacement. Be careful when using backreferences!
*
* @param {string} pattern the given pattern.
* @param {string[]} replacements a list of replacement which can be inserted into the given pattern.
* @returns {string} the pattern with all placeholders replaced with their corresponding replacements.
* @example replace(/a<<0>>a/.source, [/b+/.source]) === /a(?:b+)a/.source
*/
function replace(pattern, replacements) {
return pattern.replace(/<<(\d+)>>/g, function (m, index) {
return '(?:' + replacements[+index] + ')';
});
}
/**
* @param {string} pattern
* @param {string[]} replacements
* @param {string} [flags]
* @returns {RegExp}
*/
function re(pattern, replacements, flags) {
return RegExp(replace(pattern, replacements), flags || '');
}

/**
* Creates a nested pattern where all occurrences of the string `<<self>>` are replaced with the pattern itself.
*
* @param {string} pattern
* @param {number} depthLog2
* @returns {string}
*/
function nested(pattern, depthLog2) {
for (var i = 0; i < depthLog2; i++) {
pattern = pattern.replace(/<<self>>/g, function () { return '(?:' + pattern + ')'; });
}
return pattern.replace(/<<self>>/g, '[^\\s\\S]');
}

// https://docs.microsoft.com/en-us/azure/quantum/user-guide/language/typesystem/
// https://github.com/microsoft/qsharp-language/tree/main/Specifications/Language/5_Grammar
var keywordKinds = {
// keywords which represent a return or variable type
type: 'Unit Int BigInt Double Bool String Qubit Result Range true false Zero One Pauli PauliI PauliX PauliY PauliZ Adj Ctl',
fedonman marked this conversation as resolved.
Show resolved Hide resolved
// keywords which are used to declare a type
typeDeclaration: 'newtype',
// all other keywords
other: 'Adjoint adjoint and apply as auto body borrow borrowing Controlled controlled distribute elif else fail fixup for function if in internal intrinsic invert is let mutable namespace new not open operation or repeat return self set until use using while within'
}
// keywords
function keywordsToPattern(words) {
return '\\b(?:' + words.trim().replace(/ /g, '|') + ')\\b';
}
var typeDeclarationKeywords = keywordsToPattern(keywordKinds.typeDeclaration);
fedonman marked this conversation as resolved.
Show resolved Hide resolved
var keywords = RegExp(keywordsToPattern(keywordKinds.type + ' ' + keywordKinds.typeDeclaration + ' ' + keywordKinds.other));
var nonTypeKeywords = keywordsToPattern(keywordKinds.typeDeclaration + ' ' + keywordKinds.other);

// types
var generic = nested(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source, 2); // the idea behind the other forbidden characters is to prevent false positives. Same for tupleElement.
var nestedRound = nested(/\((?:[^()]|<<self>>)*\)/.source, 2);
var name = /@?\b[A-Za-z_]\w*\b/.source;
fedonman marked this conversation as resolved.
Show resolved Hide resolved
var genericName = replace(/<<0>>(?:\s*<<1>>)?/.source, [name, generic]);
var identifier = replace(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source, [nonTypeKeywords, genericName]);
var array = /\[\s*(?:,\s*)*\]/.source;
var typeExpressionWithoutTuple = replace(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source, [identifier, array]);
var tupleElement = replace(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source, [generic, nestedRound, array])
var tuple = replace(/\(<<0>>+(?:,<<0>>+)+\)/.source, [tupleElement]);
var typeExpression = replace(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source, [tuple, identifier, array]);

var typeInside = {
'keyword': keywords,
'punctuation': /[<>()?,.:[\]]/
};

// strings & characters
var character = /'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source; // simplified pattern
fedonman marked this conversation as resolved.
Show resolved Hide resolved
var regularString = /"(?:\\.|[^\\"\r\n])*"/.source;
fedonman marked this conversation as resolved.
Show resolved Hide resolved

// attributes
var regularStringOrCharacter = regularString + '|' + character;
var regularStringCharacterOrComment = replace(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source, [regularStringOrCharacter]);

Prism.languages.qsharp = Prism.languages.extend('clike', {
fedonman marked this conversation as resolved.
Show resolved Hide resolved
'string': [
{
pattern: re(/(^|[^$\\])<<0>>/.source, [regularString]),
lookbehind: true,
greedy: true
},
{
pattern: RegExp(character),
greedy: true,
alias: 'character'
}
],
'class-name': [
{
// open Microsoft.Quantum.Canon;
pattern: re(/(\bopen\s+)<<0>>(?=\s*;)/.source, [identifier]),
fedonman marked this conversation as resolved.
Show resolved Hide resolved
lookbehind: true,
inside: typeInside
},
{
// namespace Quantum.App1;
pattern: re(/(\bnamespace\s+)<<0>>(?=\s*{)/.source, [identifier]),
lookbehind: true,
inside: typeInside
},
],
'keyword': keywords,
'number': /(?:0(?:x[\da-f_]*[\da-f]|b[01_]*[01]|o[0-7]*[0-7])|(?:\B\.\d*|\b\d+(?:\.\d*)?)(?:e[-+]?\d+)?)l?\b/i,
fedonman marked this conversation as resolved.
Show resolved Hide resolved
'operator': /and=|or=|<[-=]|[-=]>|[*^=\-!+\/%=]=?|>>>=?|<<<=?|\^\^\^=?|\|\|\|=?|&&&=?|w\/=?|\.\.\.|~~~/,
fedonman marked this conversation as resolved.
Show resolved Hide resolved
'punctuation': /::|[{}[\];(),.:]/
});

Prism.languages.insertBefore('qsharp', 'number', {
'range': {
pattern: /\.\./,
alias: 'operator'
}
});

// string interpolation
var formatString = /:[^}\r\n]+/.source;

// single line
var sInterpolationRound = nested(replace(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source, [regularStringOrCharacter]), 2)
var sInterpolation = replace(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source, [sInterpolationRound, formatString]);

function createInterpolationInside(interpolation, interpolationRound) {
return {
'interpolation': {
pattern: re(/((?:^|[^{])(?:\{\{)*)<<0>>/.source, [interpolation]),
lookbehind: true,
inside: {
'format-string': {
pattern: re(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source, [interpolationRound, formatString]),
lookbehind: true,
inside: {
'punctuation': /^:/
}
},
'punctuation': /^\{|\}$/,
'expression': {
pattern: /[\s\S]+/,
alias: 'language-csharp',
inside: Prism.languages.csharp
fedonman marked this conversation as resolved.
Show resolved Hide resolved
}
}
},
'string': /[\s\S]+/
};
}

Prism.languages.insertBefore('qsharp', 'string', {
'interpolation-string': {
pattern: re(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source, [sInterpolation]),
lookbehind: true,
greedy: true,
inside: createInterpolationInside(sInterpolation, sInterpolationRound),
fedonman marked this conversation as resolved.
Show resolved Hide resolved
}
});

}(Prism));

Prism.languages.qs = Prism.languages.qsharp;
1 change: 1 addition & 0 deletions components/prism-qsharp.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions examples/prism-qsharp.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<h2>Full example</h2>
<pre><code>namespace Bell {
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;

operation SetQubitState(desired : Result, target : Qubit) : Unit {
if desired != M(target) {
X(target);
}
}

@EntryPoint()
operation TestBellState(count : Int, initial : Result) : (Int, Int) {

mutable numOnes = 0;
use qubit = Qubit();
for test in 1..count {
SetQubitState(initial, qubit);
let res = M(qubit);

// Count the number of ones we saw:
if res == One {
set numOnes += 1;
}
}

SetQubitState(Zero, qubit);

// Return number of times we saw a |0> and number of times we saw a |1>
Message("Test results (# of 0s, # of 1s): ");
return (count - numOnes, numOnes);
}
}</code></pre>
2 changes: 2 additions & 0 deletions plugins/autoloader/prism-autoloader.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
],
"purebasic": "clike",
"purescript": "haskell",
"qsharp": "clike",
"qml": "javascript",
"qore": "clike",
"racket": "scheme",
Expand Down Expand Up @@ -214,6 +215,7 @@
"pbfasm": "purebasic",
"purs": "purescript",
"py": "python",
"qs": "qsharp",
"rkt": "racket",
"rpy": "renpy",
"robot": "robotframework",
Expand Down
Loading