Skip to content

Commit

Permalink
feat(compiler): warning if unsupported package manager is used (#6961)
Browse files Browse the repository at this point in the history
Adding a small warning to help users encountering issues using winglibs with other JavaScript package managers. (#6129). Screenshot of what the diagnostic looks like:

<img width="631" alt="Screenshot 2024-07-29 at 7 34 50 PM" src="https://github.com/user-attachments/assets/96045db0-0659-4434-a9f9-658d0d6b46c7">

I ended up also removing some code for injecting panics into the compiler that has seldom been used in my experience (it introduced some snapshot regressions and removing the code seemed like the simpler fix).

## Checklist

- [ ] Title matches [Winglang's style guide](https://www.winglang.io/contributing/start-here/pull_requests#how-are-pull-request-titles-formatted)
- [ ] Description explains motivation and solution
- [ ] Tests added (always)
- [ ] Docs updated (only required for features)
- [ ] Added `pr/e2e-full` label if this feature requires end-to-end testing

*By submitting this pull request, I confirm that my contribution is made under the terms of the [Wing Cloud Contribution License](https://github.com/winglang/wing/blob/main/CONTRIBUTION_LICENSE.md)*.
  • Loading branch information
Chriscbr authored Jul 30, 2024
1 parent a4df3e3 commit b200bde
Show file tree
Hide file tree
Showing 29 changed files with 162 additions and 526 deletions.
6 changes: 3 additions & 3 deletions apps/wing/src/commands/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export async function compile(entrypoint?: string, options?: CompileOptions): Pr
const result = [];

for (const diagnostic of diagnostics) {
const { message, span, annotations, hints } = diagnostic;
const { message, span, annotations, hints, severity } = diagnostic;
const files: File[] = [];
const labels: Label[] = [];

Expand Down Expand Up @@ -145,7 +145,7 @@ export async function compile(entrypoint?: string, options?: CompileOptions): Pr
files,
{
message,
severity: "error",
severity,
labels,
notes: hints.map((hint) => `hint: ${hint}`),
},
Expand All @@ -156,7 +156,7 @@ export async function compile(entrypoint?: string, options?: CompileOptions): Pr
);
result.push(diagnosticText);
}
throw new Error(result.join("\n"));
throw new Error(result.join("\n").trimEnd());
} else if (error instanceof wingCompiler.PreflightError) {
let output = await prettyPrintError(error.causedBy, {
chalk,
Expand Down
8 changes: 0 additions & 8 deletions examples/tests/invalid/panic.test.w

This file was deleted.

9 changes: 0 additions & 9 deletions examples/tests/valid/debug_env.test.w

This file was deleted.

5 changes: 0 additions & 5 deletions libs/tree-sitter-wing/grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ module.exports = grammar({
$.struct_definition,
$.enum_definition,
$.try_catch_statement,
$.compiler_dbg_env,
$.super_constructor_statement,
$.throw_statement,
$.lift_statement
Expand Down Expand Up @@ -377,7 +376,6 @@ module.exports = grammar({
$.parenthesized_expression,
$.json_literal,
$.struct_literal,
$.compiler_dbg_panic,
$.optional_unwrap,
$.intrinsic
),
Expand Down Expand Up @@ -463,9 +461,6 @@ module.exports = grammar({
)
),

compiler_dbg_panic: ($) => "😱",
compiler_dbg_env: ($) => seq("🗺️", optional(";")),

call: ($) =>
prec.left(
PREC.CALL,
Expand Down
33 changes: 0 additions & 33 deletions libs/tree-sitter-wing/src/grammar.json

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

12 changes: 0 additions & 12 deletions libs/tree-sitter-wing/test/corpus/expressions.txt
Original file line number Diff line number Diff line change
Expand Up @@ -500,18 +500,6 @@ nil;
(expression_statement
(nil_value)))

================================================================================
Debug panic
================================================================================

😱;

--------------------------------------------------------------------------------

(source
(expression_statement
(compiler_dbg_panic)))

================================================================================
Duration
================================================================================
Expand Down
11 changes: 0 additions & 11 deletions libs/tree-sitter-wing/test/corpus/statements/statements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -529,17 +529,6 @@ if let var x = y {}
(reference_identifier))
block: (block)))

================================================================================
Debug symbol env
================================================================================

🗺️;

--------------------------------------------------------------------------------

(source
(compiler_dbg_env))

================================================================================
Super constructor
================================================================================
Expand Down
6 changes: 3 additions & 3 deletions libs/wingc/examples/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ pub fn main() {
let source_path = Utf8Path::new(&args[1]).canonicalize_utf8().unwrap();
let target_dir: Utf8PathBuf = env::current_dir().unwrap().join("target").try_into().unwrap();

let results = compile(source_path.parent().unwrap(), &source_path, None, &target_dir);
if results.is_err() {
let mut diags = get_diagnostics();
let _ = compile(source_path.parent().unwrap(), &source_path, None, &target_dir);
let mut diags = get_diagnostics();
if !diags.is_empty() {
// Sort error messages by line number (ascending)
diags.sort();
eprintln!(
Expand Down
2 changes: 0 additions & 2 deletions libs/wingc/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,6 @@ pub enum StmtKind {
catch_block: Option<CatchBlock>,
finally_statements: Option<Scope>,
},
CompilerDebugEnv,
ExplicitLift(ExplicitLift),
}

Expand Down Expand Up @@ -677,7 +676,6 @@ pub enum ExprKind {
element: Box<Expr>,
},
FunctionClosure(FunctionDefinition),
CompilerDebugPanic,
}

#[derive(Debug)]
Expand Down
29 changes: 2 additions & 27 deletions libs/wingc/src/comp_ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{

use strum::{Display, EnumString};

use crate::diagnostic::{report_diagnostic, Diagnostic, WingSpan};
use crate::diagnostic::{report_diagnostic, Diagnostic, DiagnosticSeverity, WingSpan};

/// The different phases of compilation, used for tracking compilation context
/// for diagnostic purposes. Feel free to add new phases as needed.
Expand Down Expand Up @@ -64,32 +64,6 @@ impl CompilationContext {
}
}

/// Macro used for explicit panics if the environment variable `WINGC_DEBUG_PANIC` is set.
/// This can be used if we want to conditionally panic in certain situations.
/// This is a macro and not a function so we can get the location of the caller
/// in the panic message.
#[macro_export]
macro_rules! dbg_panic {
() => {{
|| -> () {
// Get environment variable to see if we should panic or not
let Ok(dbg_panic) = std::env::var("WINGC_DEBUG_PANIC") else {
return;
};

if dbg_panic == "1"
|| dbg_panic == "true"
|| (dbg_panic
.parse::<$crate::comp_ctx::CompilationPhase>()
.map(|p| p == $crate::comp_ctx::CompilationContext::get_phase())
.unwrap_or(false))
{
panic!("User invoked panic");
}
}();
}};
}

pub fn set_custom_panic_hook() {
std::panic::set_hook(Box::new(|pi| {
// Print backtrace if RUST_BACKTRACE=1
Expand All @@ -109,6 +83,7 @@ pub fn set_custom_panic_hook() {
span: Some(CompilationContext::get_span()),
annotations: vec![],
hints: vec![],
severity: DiagnosticSeverity::Error,
})
}));
}
18 changes: 16 additions & 2 deletions libs/wingc/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ pub struct Diagnostic {
pub annotations: Vec<DiagnosticAnnotation>,
pub span: Option<WingSpan>,
pub hints: Vec<String>,
pub severity: DiagnosticSeverity,
}

impl Diagnostic {
Expand All @@ -290,6 +291,7 @@ impl Diagnostic {
span: Some(span.span()),
annotations: vec![],
hints: vec![],
severity: DiagnosticSeverity::Error,
}
}

Expand All @@ -316,6 +318,11 @@ impl Diagnostic {
new
}

pub fn severity(mut self, level: DiagnosticSeverity) -> Self {
self.severity = level;
self
}

pub fn report(self) {
report_diagnostic(self);
}
Expand All @@ -336,6 +343,13 @@ impl DiagnosticAnnotation {
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DiagnosticSeverity {
Error,
Warning,
}

impl std::fmt::Display for Diagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(span) = &self.span {
Expand Down Expand Up @@ -374,7 +388,7 @@ impl PartialOrd for Diagnostic {
}

thread_local! {
pub static DIAGNOSTICS: RefCell<Diagnostics> = RefCell::new(Diagnostics::new());
static DIAGNOSTICS: RefCell<Diagnostics> = RefCell::new(Diagnostics::new());
}

/// Report a compilation diagnostic
Expand Down Expand Up @@ -411,7 +425,7 @@ extern "C" {
pub fn found_errors() -> bool {
DIAGNOSTICS.with(|diagnostics| {
let diagnostics = diagnostics.borrow();
!diagnostics.is_empty()
diagnostics.iter().any(|d| d.severity == DiagnosticSeverity::Error)
})
}

Expand Down
1 change: 0 additions & 1 deletion libs/wingc/src/dtsify/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,6 @@ impl<'a> DTSifier<'a> {
| StmtKind::Assignment { .. }
| StmtKind::Scope(_)
| StmtKind::TryCatch { .. }
| StmtKind::CompilerDebugEnv
| StmtKind::ExplicitLift(_) => {}
}

Expand Down
3 changes: 2 additions & 1 deletion libs/wingc/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{

use camino::{Utf8Path, Utf8PathBuf};

use crate::diagnostic::Diagnostic;
use crate::diagnostic::{Diagnostic, DiagnosticSeverity};

#[derive(Debug)]
pub enum FilesError {
Expand All @@ -32,6 +32,7 @@ impl From<FilesError> for Diagnostic {
span: None,
annotations: vec![],
hints: vec![],
severity: DiagnosticSeverity::Error,
}
}
}
Expand Down
18 changes: 5 additions & 13 deletions libs/wingc/src/fold.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use crate::{
ast::{
ArgList, BringSource, CalleeKind, CatchBlock, Class, ClassField, ElifBlock, ElifLetBlock, Elifs, Enum,
ExplicitLift, Expr, ExprKind, FunctionBody, FunctionDefinition, FunctionParameter, FunctionSignature, IfLet,
Interface, InterpolatedString, InterpolatedStringPart, Intrinsic, LiftQualification, Literal, New, Reference,
Scope, Stmt, StmtKind, Struct, StructField, Symbol, TypeAnnotation, TypeAnnotationKind, UserDefinedType,
},
dbg_panic,
use crate::ast::{
ArgList, BringSource, CalleeKind, CatchBlock, Class, ClassField, ElifBlock, ElifLetBlock, Elifs, Enum, ExplicitLift,
Expr, ExprKind, FunctionBody, FunctionDefinition, FunctionParameter, FunctionSignature, IfLet, Interface,
InterpolatedString, InterpolatedStringPart, Intrinsic, LiftQualification, Literal, New, Reference, Scope, Stmt,
StmtKind, Struct, StructField, Symbol, TypeAnnotation, TypeAnnotationKind, UserDefinedType,
};

/// Similar to the `visit` module in `wingc` except each method takes ownership of an
Expand Down Expand Up @@ -199,7 +196,6 @@ where
}),
finally_statements: finally_statements.map(|statements| f.fold_scope(statements)),
},
StmtKind::CompilerDebugEnv => StmtKind::CompilerDebugEnv,
StmtKind::SuperConstructor { arg_list } => StmtKind::SuperConstructor {
arg_list: f.fold_args(arg_list),
},
Expand Down Expand Up @@ -391,10 +387,6 @@ where
element: Box::new(f.fold_expr(*element)),
},
ExprKind::FunctionClosure(def) => ExprKind::FunctionClosure(f.fold_function_definition(def)),
ExprKind::CompilerDebugPanic => {
dbg_panic!(); // Handle the debug panic expression (during folding)
ExprKind::CompilerDebugPanic
}
};
Expr {
id: node.id,
Expand Down
Loading

0 comments on commit b200bde

Please sign in to comment.